0
\$\begingroup\$

Part 1:

The task involves analyzing an environmental report from an oasis using the Oasis And Sand Instability Sensor (OASIS). The report consists of multiple histories, each containing a sequence of values over time. The goal is to predict the next value in each history by creating a sequence of differences at each step. This process is repeated until a sequence of zeroes is obtained, and the next values are extrapolated. The sum of these extrapolated values is the solution.

For example:

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

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.

#!/usr/bin/env python3

from pathlib import Path
from typing import Iterable

import typer


def find_next_val(line: str) -> int:
    # N1 N2 N3 N4 ...
    seqs = [list(map(int, line.split()))]

    while True:
        new = [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)]
        seqs.append(new)

        if all(val == 0 for val in new):
            break
    last = 0

    for seq in reversed(seqs[:-1]):
        seq.append(last := seq[-1] + last)

    return seqs[0][-1]


def total_values(lines: Iterable[str]) -> int:
    return sum(map(find_next_val, lines))


def main(history_file: Path) -> None:
    with open(history_file) as f:
        print(total_values(f))


if __name__ == "__main__":
    typer.run(main)

Part 2:

In Part Two, the task extends to extrapolating values backward in time for each history. The process involves adding a zero to the beginning of the sequence of zeroes and filling in new first values for each previous sequence. The goal is to determine the previous values for each history and calculate their sum.

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.

#!/usr/bin/env python3

from pathlib import Path
from typing import Iterable

import typer


def find_next_val(line: str) -> int:
    # N1 N2 N3 N4 ...
    seqs = [list(map(int, line.split()))]

    while True:
        seqs.append(
            [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)]
        )

        if all(val == 0 for val in seqs[-1]):
            break

    last = 0
    for seq in reversed(seqs[:-1]):
        seq.insert(0, last := seq[0] - last)
    return seqs[0][0]


def total_values(lines: Iterable[str]) -> int:
    return sum(map(find_next_val, lines))


def main(history_file: Path) -> None:
    with open(history_file) as f:
        print(total_values(f))


if __name__ == "__main__":
    typer.run(main)

Review Request:

General coding comments, style, etc.

What are some possible simplifications? What would you do differently?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The first thing to observe is that the code produces the correct answers to Day 9. Well done!

Describe What the Code Does Inside the Code

Even if it's a one-line description such as "Solves part 1 of 2023 Advent of Code Day 9" with a link to the problem description as a comment but preferably as a docstring, you should be including a description in your code. Other comments that could help clarify what the code is doing would also be helpful.

Efficiency Improvements

You have in Part 1's function find_next_val the following:

...
def find_next_val(line: str) -> int:
    ...
    while True:
        new = [-1 * (seqs[-1][i] - seqs[-1][i + 1]) for i in range(len(seqs[-1]) - 1)]

I would recode the last line as:

        deltas = [seqs[-1][i + 1] - seqs[-1][i] for i in range(len(seqs[-1]) - 1)]

This eliminates the multiplication by -1 and is, I believe, clearer. I would also suggest the name deltas is more descriptive as what is being calculated is the difference (delta) between successive elements.

Later in this function you have:

    ...
    last = 0
    for seq in reversed(seqs[:-1]):
        seq.append(last := seq[-1] + last)
    return seqs[0][-1]

But there is no need for this calculation to update the seq list. These statements can be simplified to:

    last = 0
    for seq in reversed(seqs[:-1]):
        last += seq[-1]
    return last

Refactor Your Code to Handle Both Parts

The find_next_val implementations for Part 1 and Part 2 are practically identical except for the direction in which we are calculating history (forward or backwards). You could have a single find_next_val function that can handle both parts if you pass it an additional forward boolean argument that specifies the direction in which we are computing history:

#!/usr/bin/env python3

from pathlib import Path
from typing import Iterable
from functools import partial

import typer


def find_next_val(line: str, forward: bool) -> int:
    # N1 N2 N3 N4 ...
    seqs = [list(map(int, line.split()))]

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

        if all(val == 0 for val in deltas):
            break

    n = 0
    for seq in reversed(seqs[:-1]):
        n = seq[-1] + n if forward else seq[0] - n

    return n


def total_values(lines: Iterable[str], forward: bool) -> int:
    return sum(map(partial(find_next_val, forward=forward), lines))


def main(history_file: Path) -> None:
    """Solves Part 1 and Part 2 of Day 9 Adevnt of Code.
    See: https://adventofcode.com/2023/day/9"""


    # We could read in the file only once with f.readlines()
    # to be used for both parts if we are sure that the lines are not modified, which
    # apppears to be the case:
    """
    with open(history_file) as f:
        lines = f.readlines()
    print(total_values(lines, True))
    print(total_values(lines, False)
    """
    # But we will stick with processing the file twice:

    for forward in (True, False):
        with open(history_file) as f:
            print(total_values(f, forward))


if __name__ == "__main__":
    typer.run(main)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.