Advent of code - Day 7
Quentin Ménoret
Posted on December 8, 2020
Are you participating in the Advent of code this year?
If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!
I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.
For day #7, I created a sort a tree like structure, but flat (I'm lazy), represented by a Record. Basically, for each color, you know which colors you can contains.
Once you have such a structure, finding the answer is just a matter of a small recursion:
const tree = input.reduce((tree, line) => {
const color = /(^.*) bags contain/.exec(line)[1];
tree[color] = [];
const matches = line.matchAll(/,? (\d+) ([^,.]*) bags?/g);
for (const match of matches) {
for (let i = 0; i < parseInt(match[1]); i++) {
tree[color].push(match[2]);
}
}
return tree;
}, {});
const depth = (color) => {
if (tree[color] === []) return 1;
return tree[color].reduce((acc, color) => acc + depth(color), 1);
};
console.log(depth("shiny gold") - 1);
Feel free to share your solution in the comments!
Photo by Markus Spiske on Unsplash
Posted on December 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.