Day 9, part 2
Day 9 challenge of the mighty Advent of Code 2024
Created at:
Last updated:
Table of Contents
Introduction
Welcome to the par two of day 8 puzzle. First part is described in Day 9, part 1. Please get familiar with the part 1 before jumping into this article. This part of the challenge is available only when you successfully finished the part 1. The second part of the challenge is described under section here.
New problem
So, as you remember, in the first part we were predicting the next value for a given sequence of numbers. Now we are asked to calculate the preceding number instead and give the sum of those number as a final result. Let's do the analysis on the test data once more.
From here we know that is and is . For the remaining two lines of test data the predictions are and respectively. This gives us a sum of .
Solution
Basically we have to do exactly what we did before, not for the last value in the array this time, but for the first one.
Refactor
Before we start looking for the prediction of the previous values let's clean up a little. That's how the updated function looks now:
If we run this we still get the same results for our test data as before, so we can safely commit the changes.
Predict previous steps
As said before, to get the previous prediction instead on the next one we just have to look at the beginning of each array and predict the previous number. Here how the function can look like:
Running this gives us:
If you now scroll up to the calculation we did manually, you can see that these are the expected results. Let's commit the changes.
Sum them together
Lets sum the numbers from previous step together.
After running this code we get:
This is the result we were expecting from our analysis, so we can save the changes.
Final result
Now it is time to replace the test data with the puzzles' real input stored in the text file. When we now run our code, the final result we get is:
Uploading this number to the form on the website shows us that we did everything the proper way. Congrats y'all!
We can now commit the final result, and call it a day.