advent-of-code 8 min read

[Day 9] Mirage Maintenance // Advent of Code 2023 (Python)

A Python walkthrough of Advent of Code 2023 Day 9: extrapolating the next and previous values of sequences by repeatedly taking differences.

Mirage Maintenance (via DALL-E 3)

Mirage Maintenance (via DALL-E 3)

Advent of Code
You ride the camel through the sandstorm and stop where the ghost’s maps told you to stop. The sandstorm subsequently…adventofcode.com


Part One

You ride the camel through the sandstorm and stop where the ghost’s maps told you to stop. The sandstorm subsequently subsides, somehow seeing you standing at an oasis!

The camel goes to get some water and you stretch your neck. As you look up, you discover what must be yet another giant floating island, this one made of metal! That must be where the parts to fix the sand machines come from.

There’s even a hang glider partially buried in the sand here; once the sun rises and heats up the sand, you might be able to use the glider and the hot air to get all the way up to the metal island!

While you wait for the sun to rise, you admire the oasis hidden here in the middle of Desert Island. It must have a delicate ecosystem; you might as well take some ecological readings while you wait. Maybe you can report any environmental instabilities you find to someone so the oasis can be around for the next sandstorm-worn traveler.

You pull out your handy Oasis And Sand Instability Sensor and analyze your surroundings. The OASIS produces a report of many values and how they are changing over time (your puzzle input). Each line in the report contains the history of a single value. For example:

0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45

To best protect the oasis, your environmental report should include a prediction of the next value in each history. To do this, start by making a new sequence from the difference at each step of your history. If that sequence is not all zeroes, repeat this process, using the sequence you just generated as the input sequence. Once all of the values in your latest sequence are zeroes, you can extrapolate what the next value of the original history should be.

In the above dataset, the first history is 0 3 6 9 12 15. Because the values increase by 3 each step, the first sequence of differences that you generate will be 3 3 3 3 3. Note that this sequence has one fewer value than the input sequence because at each step it considers two numbers from the input. Since these values aren’t all zero, repeat the process: the values differ by 0 at each step, so the next sequence is 0 0 0 0. This means you have enough information to extrapolate the history! Visually, these sequences can be arranged like this:

0 3 6 9 12 15
3 3 3 3 3
0 0 0 0

To extrapolate, start by adding a new zero to the end of your list of zeroes; because the zeroes represent differences between the two values above them, this also means there is now a placeholder in every sequence above it:

0 3 6 9 12 15 B
3 3 3 3 3 A
0 0 0 0 0

You can then start filling in placeholders from the bottom up. A needs to be the result of increasing 3 (the value to its left) by 0 (the value below it); this means A must be 3:

0 3 6 9 12 15 B
3 3 3 3 3 3
0 0 0 0 0

Finally, you can fill in B, which needs to be the result of increasing 15(the value to its left) by 3 (the value below it), or 18:

0 3 6 9 12 15 18
3 3 3 3 3 3
0 0 0 0 0

So, the next value of the first history is 18.

Finding all-zero differences for the second history requires an additional sequence:

1 3 6 10 15 21
2 3 4 5 6
1 1 1 1
0 0 0

Then, following the same process as before, work out the next value in each sequence from the bottom up:

1 3 6 10 15 21 28
2 3 4 5 6 7
1 1 1 1 1
0 0 0 0

So, the next value of the second history is 28.

The third history requires even more sequences, but its next value can be found the same way:

10 13 16 21 30 45 68
3 3 5 9 15 23
0 2 4 6 8
2 2 2 2
0 0 0

So, the next value of the third history is 68.

If you find the next value for each history in this example and add them together, you get 114.

Analyze your OASIS report and extrapolate the next value for each history. What is the sum of these extrapolated values?


Reading the question, it’s clear that we need to find the next value in each sequence and return the sum of all new extrapolated values to get the answers.

💭 Looking at the example, we can observe that in each row of historical_values , we are just generating a new sequence by doing list[i+1] — list[i] till our new list just has all the 0’s.

Then we are just adding another 0 at bottom and working our way up to generate the new number! Here’s a rough explaination from my notes:

Looking at more examples given in question:

1   3   6  10  15  21  *28*
  2   3   4   5   6   *7*
    1   1   1   1   *1*
      0   0   0   *0*
10  13  16  21  30  45  *68*
   3   3   5   9  15  *23*
     0   2   4   6   *8*
       2   2   2   *2*
         0   0  *0*

💡I can observe that, we don’t really need to generate a new value for each sequence in the stack as we only care about the top value (ex: 18, 28, 68 in above examples).

We can just do a sum of the last value in each sequence and get that number easily.

Let’s test our hypothesis, first things first, let’s setup our base test case:

And we will “extrapolate” our code from here ;) get it? no? okay!

And we will “extrapolate” our code from here ;) get it? no? okay!

Now, let’s write some logic based on our idea above:

And voila! First try 😎

[Running] python3 "/Users/jmalik/github/advent-of-code-2023/day_9/mirage_maintenance.py"
✅ process_oasis_report passed

Let’s run this code for our puzzle input?

[Running] python3 "/Users/jmalik/github/advent-of-code-2023/day_9/mirage_maintenance.py"
✅ process_oasis_report passed
Sum of extrapolated values: xxxxx

We have a value, let’s put this in answer box and…

Haha! It was too good to be true!

Haha! It was too good to be true!

Worth a try, I guess!

Let’s look at some of the possible edge cases here?

Found it! There’s a bug in how I was checking if all the numbers in a sequences are 0s. sum(next_sequence) == 0 if incorrect as it will give true for [-1, 1] as well. 🤦‍♂

We can use python’s all operator here

We can use python’s `all` operator here

Fixed code

Fixed code

Let’s run for our test cases and puzzle input:

[Running] python3 "/Users/jmalik/github/advent-of-code-2023/day_9/mirage_maintenance.py"
✅ process_oasis_report passed
Sum of extrapolated values: xxxxx

And put this new value into our answer box 🙌

Correct answer!

Correct answer!

Here’s our Pythonic code till now:

# --- Day 9: Mirage Maintenance ---

class OasisAnalyzer:
    def __init__(self, report):
        self.report = report.splitlines()

    def get_extrapolated_value(self, history_line):
        sequence = [int(x) for x in history_line.split(" ")]
        sequences = [sequence]

        while True:
            next_sequence = [sequences[-1][i + 1] - sequences[-1][i] for i in range(len(sequences[-1]) - 1)]
            sequences.append(next_sequence)

            if all(v == 0 for v in next_sequence):
                break

        return sum(row[-1] for row in sequences)

    def process_report(self):
        return sum(self.get_extrapolated_value(row) for row in self.report)

def part_one():
    with open("day_9/input.txt", "r") as f:
        report = f.read()

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report()
    print(f"Sum of extrapolated values: {sum_of_extrapolated_values}")

def test_process_oasis_report():
    report = """0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45"""

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report()
    assert sum_of_extrapolated_values == 114, f"Expected 114, got {sum_of_extrapolated_values}"
    print("✅ process_oasis_report passed")

if __name__ == "__main__":
    test_process_oasis_report()
    part_one()

Part Two

Of course, it would be nice to have even more history included in your report. Surely it’s safe to just extrapolate backwards as well, right?

For each history, repeat the process of finding differences until the sequence of differences is entirely zero. Then, rather than adding a zero to the end and filling in the next values of each previous sequence, you should instead add a zero to the beginning of your sequence of zeroes, then fill in new first values for each previous sequence.

In particular, here is what the third example history looks like when extrapolating back in time:

5 10 13 16 21 30 45
5 3 3 5 9 15
-2 0 2 4 6
2 2 2 2
0 0 0

Adding the new values on the left side of each sequence from bottom to top eventually reveals the new left-most history value: 5.

Doing this for the remaining example data above results in previous values of -3 for the first history and 0 for the second history. Adding all three new values together produces 2.

Analyze your OASIS report again, this time extrapolating the previous value for each history. What is the sum of these extrapolated values?


So, we’re tasked with a twist — extrapolating backwards to unearth the previous value in each sequence.

💭 This time, our goal is to find the previous value in each sequence and sum them up. Unlike Part One, where we added a zero at the bottom-right and worked our way up, we now add a zero at the beginning and unravel the new first values of each sequence working our way up!

Here’s a snippet from my notebook to illustrate the concept:

Let’s write a testcase first:

With our hypothesis in hand, it’s time to write the code. We’ll modify our OasisAnalyzer class, adding the method extrapolate_previous_value. This method will handle the backward extrapolation process.

Let’s check our test cases!

[Running] python3 "/Users/jmalik/github/advent-of-code-2023/day_9/mirage_maintenance.py"
✅ process_oasis_report_backward passed

🎉 Success on the first try! Now, let’s apply this to our puzzle input.

And now loading up our input and running it against new function:

[Running] python3 "/Users/jmalik/github/advent-of-code-2023/day_9/mirage_maintenance.py"
✅ process_oasis_report_backward passed
Sum of backward extrapolated values: xxxx

We get an answers, let’s validate that in answer box..and

Here’s the final pythonic code for both the parts:

# --- Day 9: Mirage Maintenance ---

class OasisAnalyzer:
    def __init__(self, report):
        self.report = report.splitlines()

    def extrapolate_next_value(self, history_line):
        sequence = [int(x) for x in history_line.split(" ")]
        sequences = [sequence]

        while True:
            next_sequence = [sequences[-1][i + 1] - sequences[-1][i] for i in range(len(sequences[-1]) - 1)]
            sequences.append(next_sequence)

            if all(v == 0 for v in next_sequence):
                break

        return sum(row[-1] for row in sequences)

    def extrapolate_previous_value(self, history_line):
        sequence = [int(x) for x in history_line.split(" ")]
        sequences = [sequence]

        while True:
            next_sequence = [sequences[-1][i + 1] - sequences[-1][i] for i in range(len(sequences[-1]) - 1)]
            sequences.append(next_sequence)

            if all(v == 0 for v in next_sequence):
                break

        sequences[-1] = [0] + sequences[-1]
        for i in range(len(sequences) - 2, -1, -1):
            sequences[i].insert(0, sequences[i][0] - sequences[i + 1][0])

        return sequences[0][0]

    def process_report(self, extrapolate_backwards=False):
        if extrapolate_backwards:
            return sum(self.extrapolate_previous_value(row) for row in self.report)
        
        return sum(self.extrapolate_next_value(row) for row in self.report)

def part_one():
    with open("day_9/input.txt", "r") as f:
        report = f.read()

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report()
    print(f"Sum of forward extrapolated values: {sum_of_extrapolated_values}")

def part_two():
    with open("day_9/input.txt", "r") as f:
        report = f.read()

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report(extrapolate_backwards=True)
    print(f"Sum of backward extrapolated values: {sum_of_extrapolated_values}")

def test_process_oasis_report_forward():
    report = """0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45"""

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report()
    assert sum_of_extrapolated_values == 114, f"Expected 114, got {sum_of_extrapolated_values}"
    print("✅ process_oasis_report_forward passed")

def test_process_oasis_report_backward():
    report = """0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45"""

    analyzer = OasisAnalyzer(report)
    sum_of_extrapolated_values = analyzer.process_report(extrapolate_backwards=True)
    assert sum_of_extrapolated_values == 2, f"Expected 2, got {sum_of_extrapolated_values}"
    print("✅ process_oasis_report_backward passed")

if __name__ == "__main__":
    test_process_oasis_report_forward()
    part_one()

    test_process_oasis_report_backward()
    part_two()

This problem taught me to think in reverse and adapt my approach to solve a unique challenge. Python’s flexibility and my notebook of ideas made it a smooth journey. What a way to ensure the Oasis’s past and future are well preserved!


p.s: I am deliberating not adding answers here so you can actually spend some time trying to understand how we solved the problem!

Feel free to checkout code on my Github repo and try to set it up and run on your machine 👇

GitHub - jatinkrmalik/advent-of-code-2023: This is my live attempt to solve all 25 problems of…
This is my live attempt to solve all 25 problems of Advent of Code 2023 with Python! - GitHub …github.com

Leave a comment

Keep reading

advent-of-code 2 min

🎄Solve Advent of Code 2024 With Me!

Announcing a spoiler-free YouTube video series for Advent of Code 2024 that focuses on how to analyze and approach each puzzle, not just the answers.