Skip to content

Instantly share code, notes, and snippets.

@Friss
Created December 7, 2020 06:06
Show Gist options
  • Save Friss/a3643966b294fd19053bafde6d5bba5c to your computer and use it in GitHub Desktop.
Save Friss/a3643966b294fd19053bafde6d5bba5c to your computer and use it in GitHub Desktop.
const fs = require('fs').promises;
(async () => {
console.log(`Reading input from ${__dirname}/${process.argv[2]}.txt`);
const inputData = await fs.readFile(`${__dirname}/${process.argv[2]}.txt`);
const inputs = inputData
.toString()
.split('\n')
.filter((n) => n);
const bagHolder = /^(?<color>\w+ \w+) bags? contain/;
const subBag = / (?<num>\d+) (?<color>\w+ \w+) bags?(?:,|.)/g;
const myBag = 'shiny gold';
const bagMap = {};
inputs.forEach((line) => {
const outerBag = bagHolder.exec(line).groups.color;
const subBags = [];
let subBagExec = subBag.exec(line);
while (subBagExec) {
subBags.push({
num: parseInt(subBagExec.groups.num, 10),
color: subBagExec.groups.color,
});
subBagExec = subBag.exec(line);
}
bagMap[outerBag] = subBags;
});
const bagCounter = new Set();
const goDown = (parentColor, bag) => {
if (bag === myBag && parentColor !== myBag) {
bagCounter.add(parentColor);
}
if (bagMap[bag].length === 0) {
return;
}
bagMap[bag].forEach((subBag) => {
return goDown(parentColor, subBag.color);
});
};
Object.keys(bagMap).forEach((outerBag) => {
goDown(outerBag, outerBag);
});
const countDownBags = (bag) => {
if (bagMap[bag].length === 0) {
return 0;
}
const sum = bagMap[bag].reduce((sum, bag) => {
return sum + bag.num * countDownBags(bag.color) + bag.num;
}, 0);
return sum;
};
console.log('outerBagCount', bagCounter.size);
console.log('bagCount', countDownBags(myBag));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment