Advent of code - Day 7

qmenoret

Quentin Ménoret

Posted on December 8, 2020

Advent of code - Day 7

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);
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

💖 💪 🙅 🚩
qmenoret
Quentin Ménoret

Posted on December 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of code - Day 23
javascript Advent of code - Day 23

December 24, 2020

Advent of code - Day 22
javascript Advent of code - Day 22

December 23, 2020

Advent of code - Day 21
javascript Advent of code - Day 21

December 22, 2020

Advent of code - Day 18
javascript Advent of code - Day 18

December 19, 2020

Advent of code - Day 17
javascript Advent of code - Day 17

December 18, 2020