Advent of code - Day 10

qmenoret

Quentin Ménoret

Posted on December 11, 2020

Advent of code - Day 10

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.

I'm already happy I managed to finish it. I know there are some incredible solutions out there (a colleague of mine solved is with a math equation 🤯), but all I could do was a brute-force. As I often say, IIWIW (If It Works It Works)!

Here is my solution for day #10:

const cache = [];

function valueFor(code, currentValue) {
  if (cache[currentValue]) return cache[currentValue];
  cache[currentValue] = resolve(code, currentValue);
  return cache[currentValue];
}

function resolve(code, currentValue = 0) {
  if (!code.length) return 1;
  const [first, second, third] = code;
  let result = 0;
  if (first - currentValue > 0 && first - currentValue <= 3)
    result += valueFor(code.slice(1), first);
  if (second - currentValue > 0 && second - currentValue <= 3)
    result += valueFor(code.slice(2), second);
  if (third - currentValue > 0 && third - currentValue <= 3)
    result += valueFor(code.slice(3), third);
  return result;
}

resolve(input)
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 11, 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