DEV Community

Cover image for Advent of code - Day 9

Advent of code - Day 9

qmenoret profile image Quentin Ménoret ・1 min read

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.

Day 9 felt surprisingly not as scary as day 8. Maybe I'm just getting better?
Here is my solution for day #9:

function resolve(code, offset) {
  for (let i = offset; i < code.length; i++) {
    const currentNumber = code[i];
    const possibleNumbers = code.slice(i - offset, i);
    const ok = possibleNumbers.some((firstNumber) =>
        (secondNumber) =>
          firstNumber + secondNumber === currentNumber &&
          firstNumber !== secondNumber
    if (!ok) return currentNumber;

function findMinMax(code, offset) {
  const invalidNumber = resolve(code, offset);
  for (let i = 0; i < code.length; i++) {
    let total = 0;
    for (let j = i; j < code.length; j++) {
      // Since the input is sorted, we just need to traverse
      // and make the sum until we find one that matches
      total += code[j];
      if (total < invalidNumber) continue;
      if (total > invalidNumber) break;
      const range = code.slice(i, j + 1);
      return Math.min(...range) + Math.max(...range);

Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!

Photo by Markus Spiske on Unsplash

Discussion (1)

Editor guide
kingsleyijomah profile image
Kingsley Ijomah

Thanks! I will check this out! love a good challenge :)