From c42b4fbf8fc997cbeb30c80dbaad4d8f85109912 Mon Sep 17 00:00:00 2001 From: Joshua Seigler Date: Mon, 7 Dec 2020 17:31:14 +0000 Subject: [PATCH] Use a map --- solutions/day7/solution.js | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/solutions/day7/solution.js b/solutions/day7/solution.js index ac9dd67..5ce261b 100644 --- a/solutions/day7/solution.js +++ b/solutions/day7/solution.js @@ -5,34 +5,24 @@ const report = (...messages) => console.log(`[${require(fromHere('../../package. async function run () { // light red bags contain 1 bright white bag, 2 muted yellow bags. - const input = (await read(fromHere('input.txt'), 'utf8')).trim().split('\n').map( + const input = new Map(); + (await read(fromHere('input.txt'), 'utf8')).trim().split('\n').forEach( line => { const [color, rest] = line.split(' bags contain ') let contents if (rest === 'no other bags.') contents = [] else { - contents = rest.slice(0, -1).split(', ').map(i => { - const [, qty, color] = i.match(/(\d+) (.+) bags?/) - return { + contents = rest.split(', ').map(i => { + const [, qty, color] = i.match(/(\d+) (.+) bags?\.?/) + return ({ quantity: 1 * qty, color - } + }) }) } - return { - color, - contents - } + input.set(color, contents) } - ).reduce((acc, cur) => ({ ...acc, [cur.color]: cur.contents }), {}) - /* -{ - color - contents: [ - { quantity, color} - ] -} -*/ + ) await solveForFirstStar(input) await solveForSecondStar(input) @@ -40,7 +30,7 @@ async function run () { async function solveForFirstStar (input) { const outerColors = new Set() - Object.entries(input).forEach(([color, contents]) => { + input.forEach((contents, color) => { if (contents.some( bag => bag.color === 'shiny gold') ) { @@ -50,8 +40,8 @@ async function solveForFirstStar (input) { let oldSize while (oldSize !== outerColors.size) { oldSize = outerColors.size - Object.entries(input).forEach( - ([color, contents]) => { + input.forEach( + (contents, color) => { if ( !outerColors.has(color) && contents.some(bag => outerColors.has(bag.color)) @@ -67,8 +57,8 @@ async function solveForFirstStar (input) { } function count (input, color) { - if (input[color].length === 0) return 1 - return input[color].reduce((acc, bag) => acc + bag.quantity * count(input, bag.color), 1) + if (input.get(color).length === 0) return 1 + return input.get(color).reduce((acc, bag) => acc + bag.quantity * count(input, bag.color), 1) } async function solveForSecondStar (input) {