Add '2020/' from commit 'aaabfa90c9033044d0a9d5fe6776b718711ef46c'

git-subtree-dir: 2020
git-subtree-mainline: ab8f135946
git-subtree-split: aaabfa90c9
This commit is contained in:
2022-01-09 17:06:15 +00:00
29 changed files with 8729 additions and 0 deletions

42
2020/07/part2.js Normal file
View File

@@ -0,0 +1,42 @@
const fs = require('fs');
const OWN_BAG = 'shiny gold';
function parseLine(line) {
let [ self, others ] = line.trim().split(" bags contain ");
if (self === undefined || others === undefined) return [];
if (others == "no other bags.") return []; // [{a: self, b: null, count: 0}];
others = others.replace(".", "").replace(/bags?/g, "").split(",");
return others.map((other) => {
let [ num, ...rest ] = other.trim().split(' ');
return { a: self, b: rest.join(' '), count: Number(num) };
});
}
fs.readFile('input', (err, data) => {
if (err) throw err;
let rules = data.toString().split("\n").map( parseLine ).flat();
let bags = {};
rules.forEach((rule) => {
let parent = bags[rule.a] || {spec: rule.a};
let child = bags[rule.b] || {spec: rule.b};
if (!child.hasOwnProperty('parent')) child.parent = parent;
if (!parent.hasOwnProperty('children')) parent.children = [];
parent.children.push({ count: rule.count, bag: child });
bags[rule.a] = parent;
bags[rule.b] = child;
});
let bagCount = function(bag, self_count) {
if (!bag.children) return self_count;
return self_count + (bag.children.map((node) => bagCount(node.bag, node.count)).reduce((a,b) => a+b) * self_count);
};
let result = bags[OWN_BAG].children.map((node) => bagCount(node.bag, node.count)).reduce((a,b) => (a+b));
console.log(result);
});