<- back

advent of code - day 9

2023-12-09

See the puzzle here.

See my full solution here.

Both parts were nearly the same code. I'm not sure if there was a trick I didn't fall for, but I knocked this one out pretty quick and barely had to modify the code between both parts.

Here's the main chunk of code from my solution:

let allDone = false;
let index = 0;

// Build the patterns
while(!allDone) {
 allDone = true;
 for(let i=0; i   const row = data[i][index];
  const diffs = [];
  for(let j=1; j    if(row[j] - row[j-1] !== 0) {
    allDone = false;
   }
   diffs.push(row[j] - row[j-1]);
  }
  data[i].push(diffs);
 }
 index++;
}

// Fill the in the last values
for(let i=0; i  for(let j=data[i].length-1; j>0; j--) {
  const diff = data[i][j][data[i][j].length-1];
  const lastElem = data[i][j-1][data[i][j-1].length-1];
  data[i][j-1].push(lastElem + diff);
 }
}

// Sum the last values
for(let i=0; i  sum += data[i][0][data[i][0].length-1];
}

console.log(sum);

Basically, while all of the values in the latest difference array aren't 0, keep looping until they all are. Then use the differences to go back and fill in the last values.

The second part is basically the same, except using the differences to go back and fill in the preceding values.