44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
|
import aocd
|
||
|
import collections
|
||
|
|
||
|
def parse_rules(orders):
|
||
|
"""
|
||
|
Return a dictionary mapping page numbers to lists of page numbers
|
||
|
For any given key, each page of the value must come after it
|
||
|
"""
|
||
|
rules = collections.defaultdict(list)
|
||
|
|
||
|
for order in orders:
|
||
|
k,v = order.split('|')
|
||
|
rules[k].append(v)
|
||
|
|
||
|
return rules
|
||
|
|
||
|
def verify_update(update, rules):
|
||
|
"""
|
||
|
Ensure that an update is valid using an O(n^2) approach that will
|
||
|
bite me in the ass in part B somehow
|
||
|
"""
|
||
|
update = update.split(',')
|
||
|
for n, page in enumerate(update):
|
||
|
for prev_page in update[:n]:
|
||
|
if prev_page in rules[page]:
|
||
|
return 0
|
||
|
return int(update[len(update)//2])
|
||
|
|
||
|
|
||
|
def solve(data):
|
||
|
orders, updates = data.split('\n\n')
|
||
|
rules = parse_rules(orders.split('\n'))
|
||
|
return sum(verify_update(u, rules) for u in updates.split('\n'))
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
puz = aocd.models.Puzzle(year=2024, day=5)
|
||
|
|
||
|
# data = puz.examples[0].input_data
|
||
|
data = puz.input_data
|
||
|
|
||
|
solution = solve(data)
|
||
|
|
||
|
print(solution)
|
||
|
aocd.submit(solution, year=2024, day=5, part='a')
|