diff options
author | Marvin Borner | 2020-12-07 17:31:15 +0100 |
---|---|---|
committer | Marvin Borner | 2020-12-07 17:31:15 +0100 |
commit | 36942621c1d8fd95bfcd6ed0e9746f9ae9416938 (patch) | |
tree | 0ca1984d1b2b994c313c45f2277059a0b833a3d4 /2020/7/solve.js | |
parent | 9dd43be0c0671303b97d1e4a2dc1727a633a5187 (diff) |
Added 7th solution
Diffstat (limited to '2020/7/solve.js')
-rw-r--r-- | 2020/7/solve.js | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/2020/7/solve.js b/2020/7/solve.js new file mode 100644 index 0000000..28359e6 --- /dev/null +++ b/2020/7/solve.js @@ -0,0 +1,49 @@ +const fs = require("fs"); +const data = fs.readFileSync("input", "utf8").split('\n'); + +function getMap() +{ + return data.reduce((map, line) => { + const [superBag, subBags] = line.split(" contain "); + const bag = superBag.split(" ").slice(0, -1).join(" "); + if (!subBags || subBags == "no other bags.") { + map[bag] = {}; + } else { + map[bag] = subBags.split(", ").reduce((subMap, bags) => { + const subBag = bags.split(" "); + const subBagName = subBag.slice(1, -1).join(" "); + subMap[subBagName] = +subBag[0]; + return subMap; + }, {}); + } + return map; + }, {}); +} + +function inBag(map, superBag, subBag) +{ + if (map[superBag][subBag]) + return true; + + return Object.keys(map[superBag]).reduce((acc, key) => acc || inBag(map, key, subBag), false); +} + +function countBags(map, bag) +{ + return Object.keys(map[bag]).reduce((acc, key) => acc + map[bag][key] * (1 + countBags(map, key)), 0); +} + +function partOne() +{ + const map = getMap(); + return Object.keys(map).reduce((n, key) => n + inBag(map, key, "shiny gold"), 0); +} + +function partTwo() +{ + const map = getMap(); + return countBags(map, "shiny gold"); +} + +console.log(partOne()); +console.log(partTwo()); |