DEV Community

Cover image for Advent of code - Day 10
Quentin Ménoret
Quentin Ménoret

Posted on

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

Top comments (0)