Day 5 - Advent of Code 2023

Working solutions for the day 5 puzzles.

Part One

""" day_05_01.py """

# usage: python3 day_05_01.py < input

import sys


def almanac(x, data):
    """ function almanac """
    for destination, source, length in data:
        if source <= x < source + length:
            return x - source + destination
    return x


_, u = sys.stdin.readline().split(': ')
values = list(map(int, u.split()))

sys.stdin.readline()

while sys.stdin.readline():
    conditions = []
    while (line := sys.stdin.readline().strip()) != '':
        conditions.append(list(map(int, line.split())))

    values = [almanac(i, conditions) for i in values]

print(min(values))

Part Two

""" day_05_02.py """

# usage: python3 day_05_02.py < input

import sys


def almanac(x, data):
    """ function almanac over range x """
    for destination, source, length in data:
        translation = - source + destination

        if source <= x.start and x.stop <= source + length:
            return [range(x.start + translation, x.stop + translation)]

        if source <= x.start <= source + length:
            return [range(x.start + translation, destination + length)] + \
                   almanac(range(source + length + 1, x.stop), data)

        if source <= x.stop <= source + length:
            return almanac(range(x.start, source - 1), data) + \
                   [range(destination, x.stop + translation)]
    return [x]


_, u = sys.stdin.readline().split(': ')
u = list(map(int, u.split()))
values = [range(u[i], u[i] + u[i + 1]) for i in range(0, len(u), 2)]

sys.stdin.readline()

while sys.stdin.readline():
    conditions = []
    while (line := sys.stdin.readline().strip()) != '':
        conditions.append(list(map(int, line.split())))

    output = []
    for i in values:
        output += almanac(i, conditions)
    values = output

print(min(i.start for i in output))