Day 5 - Advent of Code 2024
5 December 2024
Working solutions for the day 5 puzzles.
Part One
""" day_05_01.py """
# usage: python3 day_05_01.py < input
import sys
def verify(pages, order):
""" do pages align with order rules - middle or '0' """
i = len(pages)
while i > 0:
i -= 1
page = pages[i]
before = [x for x, y in order if y == page]
for j in [pages.index(p) for p in before if p in pages]:
if j > i:
return '0'
return pages[len(pages) // 2]
with sys.stdin as infile:
rules = []
rule = input()
while rule:
rules.append(rule.split('|'))
rule = input()
updates = [pages.strip().split(',') for pages in infile]
total = sum(int(verify(update, rules)) for update in updates)
print(total)
Part Two
""" day_05_02.py """
# usage: python3 day_05_02.py < input
import sys
from functools import cmp_to_key
def verify(pages, order):
""" do pages align with order rules - middle or '0' """
i = len(pages)
while i > 0:
i -= 1
page = pages[i]
before = [x for x, y in order if y == page]
for j in [pages.index(p) for p in before if p in pages]:
if j > i:
return '0'
return pages[len(pages) // 2]
def in_order(page_1, page_2):
""" are page 1 and page 2 in order -ve yes +ve no """
if [page_1, page_2] in rules:
return -1
return 1
with sys.stdin as infile:
rules = []
rule = input()
while rule:
rules.append(rule.split('|'))
rule = input()
updates = [pages.strip().split(',') for pages in infile]
invalid = [update for update in updates if verify(update, rules) == '0']
total = 0
for update in invalid:
corrected = sorted(update, key=cmp_to_key(in_order))
total += int(verify(corrected, rules))
print(total)