mirror of
https://github.com/seigler/advent-of-code-2020
synced 2025-07-27 00:06:09 +00:00
Use a map
This commit is contained in:
parent
0d10bdffca
commit
c42b4fbf8f
1 changed files with 13 additions and 23 deletions
|
@ -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) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue