Add solution for day 5

This commit is contained in:
William Brawner 2024-12-05 09:33:49 -07:00
parent 5660b8a712
commit 532175340a
Signed by: wbrawner
GPG key ID: 8FF12381C6C90D35

78
src/day05.py Normal file
View file

@ -0,0 +1,78 @@
#!/usr/bin/env python3
from math import floor
from util import read_input
def parse_input(lines):
updates = []
dependencies = {}
for line in lines:
if "|" in line:
(left, right) = line.split('|')
if right not in dependencies:
dependencies[right] = set()
dependencies[right].add(left)
elif ',' in line:
updates.append(line.split(','))
return (dependencies, updates)
# Returns the middle page number if the update is correctly ordered, else None
def find_middle(dependencies, update):
for i, page in enumerate(update):
page_dependencies = dependencies[page] if page in dependencies else []
for dependency in page_dependencies:
if dependency in update and update.index(dependency) > i:
return None
return int(update[floor(len(update) / 2)])
# sorts the update so that it's valid and returns its middle page number
def fix_order(dependencies, update):
update = list(update)
i = len(update) - 1
while i > -1:
page = update[i]
page_dependencies = dependencies[page] if page in dependencies else []
for dependency in page_dependencies:
index = update.index(dependency) if dependency in update else -1
if index > i:
del update[index]
update.insert(i, dependency)
i -= 1
middle = find_middle(dependencies, update)
if middle is None:
return fix_order(dependencies, update)
else:
return middle
def part1(input_lines):
(dependencies, updates) = parse_input(input_lines)
total = 0
for update in updates:
middle = find_middle(dependencies, update)
if middle is not None:
total += middle
return total
def part2(input_lines):
(dependencies, updates) = parse_input(input_lines)
total = 0
for update in updates:
middle = find_middle(dependencies, update)
if middle is None:
total += fix_order(dependencies, update)
return total
test_input = read_input("_test")
assert 143 == part1(test_input)
real_input = read_input()
print(part1(real_input))
assert 123 == part2(test_input)
print(part2(real_input))