DEV Community

Cover image for Advent of Code 2023 - December 9th
Rob van der Leek
Rob van der Leek

Posted on

Advent of Code 2023 - December 9th

In this series, I'll share my progress with the 2023 version of Advent of Code.

Check the first post for a short intro to this series.

You can also follow my progress on GitHub.

December 9th

The puzzle of day 9 was a breeze (which I needed a bit, to be honest).

My pitfall for this puzzle: I was afraid recursion would not cut it for this puzzle, but in the end it did and it made the code very straightforward and very concise (only 32 lines).

Solution here, do not click if you want to solve the puzzle first yourself
#!/usr/bin/env python3

with open('input.txt') as infile:
    lines = infile.readlines()

histories = []
for line in lines:
    history = [int(n) for n in line.strip().split(' ')]
    histories.append(history)

def next_value(history):
    if len([n for n in history if n == 0]) == len(history):
        return 0
    else:
        next_history = []
        for idx, n in enumerate(history):
            if idx <= len(history) - 2:
                next_history.append(history[idx + 1] - n)
        return history[-1] + next_value(next_history)

def previous_value(history):
    if len([n for n in history if n == 0]) == len(history):
        return 0
    else:
        next_history = []
        for idx, n in enumerate(history):
            if idx <= len(history) - 2:
                next_history.append(history[idx + 1] - n)
        return history[0] - previous_value(next_history)

print(sum([next_value(h) for h in histories]))
print(sum([previous_value(h) for h in histories]))
Enter fullscreen mode Exit fullscreen mode

That's it! See you again tomorrow!

Top comments (0)