
Day 9, part 1
Day 9 challenge of the mighty Advent of Code 2024
Introduction
Let me welcome you to this article where we are going to crack the advent of Code day 9 puzzle. The whole description can be read here. Please do so before moving forward, to have a good context of what we are going to do. Today we are given some sensor reading and our job is to make predictions of what the next value might be.
Understanding the problem
Let's consider the test data:
10 3 6 9 12 15
21 3 6 10 15 21
310 13 16 21 30 45And more precisely, we take the first row which is our first reading. To make a prediction of what the next value might be we need to calculate differences between each pair of number until all the differences are 0s, like so:
10 3 6 9 12 15
2 3 3 3 3 3
3 0 0 0 0As soon as we get here we have to start now from the bottom to make predictions for values in the lines above, and repeat the process until we get the prediction for the first line.
10 3 6 9 12 15 B
2 3 3 3 3 3 A
3 0 0 0 0 0Now if we know that the difference between 3 and A is 0 we know that A = 3. Now we can use this value to calculate B the same way: B - 15 = A(3), thus B equals 18.
Following the same algorithm we get 28 for the second reading and 68 for the third one.
The solution to this puzzle is to sum all this numbers together, so in case of our test data the result is 114.
Now we can talk about the solution, but first let's create necessary files.
Solution
The solution can be handled in steps:
- Parse input data - of course, we can work on text straight but why would we?
- Calculate differences between numbers as long as you end up with zeros only
- Starting from the bottom, calculate next number until we get the final result
Parse input data
Let's put the test data into a variable.
1const input = `0 3 6 9 12 15
21 3 6 10 15 21
310 13 16 21 30 45`;Parsing the data in this case is as easy as separating lines and then collecting numbers in each line into an array.
1function parseData(input) {
2 const lines = input.split('\
3');
4 return lines.map(stringToNumArray);
5}
6function stringToNumArray(string) {
7 return string
8 .trim()
9 .split(/\\s+/)
10 .map((numString) => parseInt(numString));
11}
12const inputData = parseData(input);
13console.log('Parsed numbers: ', inputData);With the piece of code above we get following results:
1Parsed numbers: [
2 [ 0, 3, 6, 9, 12, 15 ],
3 [ 1, 3, 6, 10, 15, 21 ],
4 [ 10, 13, 16, 21, 30, 45 ]
5]Looks good to me! We can now commit the changes before moving forward.
1git add .
2git commit -m "parse input data"Find the differences
We will do it in steps:
- Store the results in the
diffs, initializing with the array passed as an input. - Look at the last element in the
diffsarray, if it isn't all zeros, then calculate the new differences and push them to thediffs. - When we get to the point when the array we are currently checking is all zeros, we return the
diffs.
1function getDifferencesUntilZeros(numArray) {
2 const diffs = [numArray];
3 let currentIndex = 0;
4 while (!hasZerosOnly(diffs[currentIndex])) {
5 const newDiff = getDifferences(diffs[currentIndex]);
6 diffs.push(newDiff);
7 currentIndex++;
8 }
9 return diffs;
10}
11function hasZerosOnly(numArray) {
12 return numArray.every((num) => num === 0);
13}
14function getDifferences(numArr) {
15 const result = [];
16 for (let i = 0; i < numArr.length - 1; i++) {
17 result.push(numArr[i + 1] - numArr[i]);
18 }
19 return result;
20}
21const diffs = inputData.map(getDifferencesUntilZeros);
22console.log('Differences until zeros: ', diffs);If we run this piece of code we can see in the console the following results:
1Differences until zeros: [
2 [
3 [ 0, 3, 6, 9, 12, 15 ],
4 [ 3, 3, 3, 3, 3 ],
5 [ 0, 0, 0, 0 ]
6 ],
7 [
8 [ 1, 3, 6, 10, 15, 21 ],
9 [ 2, 3, 4, 5, 6 ],
10 [ 1, 1, 1, 1 ],
11 [ 0, 0, 0 ]
12 ],
13 [
14 [ 10, 13, 16, 21, 30, 45 ],
15 [ 3, 3, 5, 9, 15 ],
16 [ 0, 2, 4, 6 ],
17 [ 2, 2, 2 ],
18 [ 0, 0 ]
19 ]
20]If we compare this to the test data analysis on the puzzle's page and to what we have calculated earlier, we can see that this is what we need. We can save that.
1git add .
2git commit -m "find the differences until zeros"Predict next number
Now when we have all the diffs, we can use them to find our predicted value. To do so we start from the last diffs array, and we use its last value to calculate the prediction for the previous diffs. We repeat the process until we get back to the first array (with the initial numbers). All of this can be done with the following:
1function predictNextSteps(diffs) {
2 for (let i = diffs.length - 1; i > 0; i--) {
3 if (i === diffs.length - 1) {
4 diffs[i].push(0);
5 }
6 const thisLastIndex = diffs[i].length - 1;
7 const prevLastIndex = diffs[i - 1].length - 1;
8 diffs[i - 1].push(diffs[i][thisLastIndex] + diffs[i - 1][prevLastIndex]);
9 }
10 return diffs[0][diffs[0].length - 1];
11}
12const predictedNumbers = diffs.map(predictNextSteps);
13console.log('Predicted numbers: ', predictedNumbers);If we run this piece of code, it spits in the console:
1Predicted numbers: [ 18, 28, 68 ]And these are the values we previously calculated by hand. We can now commit the changes before feeding our code with the real input data.
1git add .
2git commit -m "predict next number"Final result
Now we replace the test data with input coming from the file containing the puzzles' data. We also have to add a bit of logic to sum all the predictions up. This time I did it inline.
1console.log(
2 'Final sum: ',
3 predictedNumbers.reduce((acc, curr) => (acc += curr), 0)
4);Finally, we can run the code to get the final answer.
1Final sum: 1887980197If we submitted the result to the form on the website, this appeared before our eyes:
This means we are home once again, and we can celebrate this beautiful moment, but before, let's commit the final code we made.
1git add .
2git commit -m "day 9 part 1 final result"That's all folks! See you in the Day 9, part 2!