Day 9 - Advent of Code 2023

Working solutions for the day 9 puzzles.

Part One

""" day_09_01.py """

# usage: python3 day_09_01.py < input

import sys


answer = 0

for line in sys.stdin:
    seqs = []
    seqs.append(list(map(int, line.split())))
    while [i for i in seqs[-1] if i != 0]:
        seq = seqs[-1]
        seqs.append([seq[i + 1] - seq[i] for i in range(len(seq) - 1)])

    for i in range(len(seqs) - 1, 0, -1):
        carry = seqs[i][-1] + seqs[i - 1][-1]
        seqs[i - 1].append(carry)

    answer += seqs[0][-1]

print(answer)

Part Two

""" day_09_02.py """

# usage: python3 day_09_02.py < input

import sys


answer = 0

for line in sys.stdin:
    seqs = []
    seqs.append(list(map(int, line.split())))
    while [i for i in seqs[-1] if i != 0]:
        seq = seqs[-1]
        seqs.append([seq[i + 1] - seq[i] for i in range(len(seq) - 1)])

    for i in range(len(seqs) - 1, 0, -1):
        carry = seqs[i - 1][0] - seqs[i][0]
        seqs[i - 1] = [carry] + seqs[i - 1]

    answer += seqs[0][0]

print(answer)