Created
December 7, 2020 15:03
-
-
Save cranderveldt/3f1b9698bdccdeba782d77698757ae7a to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puzzleInput = `` | |
// Part 1 | |
const parseInput = (input) => { | |
return input.split(/\n/) | |
} | |
const interpretRule = (rule) => { | |
const matches = [...rule.matchAll(/^([a-z ]+) bags contain ((\d+ [a-z ]+(, )?)+|no other bags)\.$/gi)][0] | |
const contain = matches[2].split(', ').map(str => { | |
if (str.includes('no other bags')) { | |
return { num: 0 } | |
} | |
const matches = [...str.matchAll(/(\d+) ([a-z ]+) bags?/gi)][0] | |
return { | |
num: parseInt(matches[1]), | |
name: matches[2], | |
} | |
}) | |
return { | |
name: matches[1], | |
contain: contain, | |
children: contain.map(x => x.name), | |
} | |
} | |
const findParents = (rules, targets) => { | |
return rules.filter(rule => ( | |
targets.reduce((acc, target) => acc || rule.children.includes(target), false) | |
)).map(x => x.name) | |
} | |
const fetchParents = (rules, targets, allParents) => { | |
const newParents = findParents(rules, targets) | |
if (newParents.length > 0) { | |
allParents = [...allParents, ...newParents] | |
return fetchParents(rules, newParents, allParents) | |
} | |
return allParents | |
} | |
const partOne = (input, target) => { | |
const lines = parseInput(input) | |
const rules = lines.map(interpretRule) | |
const allBags = new Set(fetchParents(rules, [target], [])) | |
console.log(allBags.size) | |
} | |
partOne(puzzleInput, 'shiny gold') | |
// Part 2 | |
const fetchChildren = (rules, target) => { | |
const parent = rules.find(rule => rule.name === target) | |
return parent.contain | |
.filter(child => !!child.name) | |
.reduce((acc, child) => { | |
return acc + child.num + (child.num * fetchChildren(rules, child.name)) | |
}, 0) | |
} | |
const partTwo = (input, target) => { | |
const lines = parseInput(input) | |
const rules = lines.map(interpretRule) | |
const bagCount = fetchChildren(rules, target) | |
console.log(bagCount) | |
} | |
partTwo(puzzleInput, 'shiny gold') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment