advent-of-code-2024/day5.2.py

55 lines
1.1 KiB
Python
Raw Permalink Normal View History

2024-12-05 11:16:53 -08:00
""" day 5 part 1 """
import fileinput
import collections
deps = collections.defaultdict(set) # map post -> [pre]
reader = fileinput.input()
for line in reader:
line = line.strip()
if not line:
break
pre,post = line.split('|')
deps[post].add(pre)
total = 0
def print_page(seq, page, deps, printed, wanted):
if page in printed:
return
for dep in deps[page]:
if dep in wanted:
print_page(seq, dep, deps, printed, wanted)
seq.append(page)
printed.add(page)
for line in reader:
seq = line.strip().split(',')
wanted = set(seq)
seen = set()
safe = True
for page in seq:
# print(f'{seen} -> {page}')
for dep in deps[page]:
if dep in wanted and dep not in seen:
# print(f' {page} missing {dep}')
safe = False
seen.add(page)
if not safe:
seq = []
printed = set()
for page in wanted:
print_page(seq, page, deps, printed, wanted)
val = int(seq[len(seq)//2])
print(f'{seq} -> {val}')
total += int(val)
print(total)