Files
python-aoc-2023/day05/part1.py
Sebastian Seedorf d636db3ca2 Day 05
2023-12-07 14:43:04 +01:00

62 lines
1.5 KiB
Python

#!/usr/bin/env python3
from typing import List, Tuple
lines = (x.strip() for x in open("input.txt"))
seeds = ()
current_map = "undef"
maps = {}
map_names = []
for line in lines:
match line:
case "" | "\n":
continue
case x if x.startswith("seeds: "):
rest = x[len("seeds: "):]
seeds = tuple(int(y) for y in rest.split(" "))
case x if x.endswith(" map:"):
rest = x[:-len(" map:")]
current_map = rest
maps[current_map] = []
map_names.append(current_map)
case x if len(x) and x[0].isdigit():
maps[current_map].append(tuple(int(y) for y in x.split(" ")))
case _:
pass
def parse_map(value: List[Tuple[int, int, int]]):
curr = 0
out = []
for dest, src, size in sorted(value, key=lambda x: x[1]):
if src > curr:
out.append((curr, 0))
if size > 0:
out.append((src, dest-src))
curr = src + size
out.append((curr, 0))
return out
print(maps)
maps = {name: parse_map(value) for name, value in maps.items()}
print(maps)
def find_largest_smaller_value(sorted_list, x):
low, high = 0, len(sorted_list)
while low < high - 1:
mid = (low + high) // 2
if sorted_list[mid][0] <= x:
low = mid
else:
high = mid
return sorted_list[low]
result = float("inf")
for seed in seeds:
for name in map_names:
seed += find_largest_smaller_value(maps[name], seed)[1]
result = min(seed, result)
print(result)