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

46 lines
1.2 KiB
Python
Raw Normal View History

2024-12-05 09:50:29 +00:00
from collections import defaultdict
from itertools import pairwise
def check_update(upd, rules):
for a, b in pairwise(upd):
if [a, b] not in rules:
return False
return True
2024-12-08 21:32:36 +00:00
def fix_update(upd, rules):
while not check_update(upd, rules):
for i in range(len(upd)):
for j in range(i+1, len(upd)):
if [upd[j], upd[i]] in rules:
upd[j], upd[i] = upd[i], upd[j]
2024-12-05 09:50:29 +00:00
def main(content):
2024-12-08 21:32:36 +00:00
rules, updates = content.split("\n\n")
rules = [x.split("|") for x in rules.split("\n")]
2024-12-05 09:50:29 +00:00
updates = [x.split(",") for x in updates.rstrip().split("\n")]
part1 = 0
2024-12-08 21:32:36 +00:00
incorrect_updates = []
2024-12-05 09:50:29 +00:00
for update in updates:
2024-12-08 21:32:36 +00:00
if check_update(update, rules):
2024-12-05 09:50:29 +00:00
middle = update[len(update)//2]
part1 += int(middle)
2024-12-08 21:32:36 +00:00
else:
incorrect_updates.append(update)
2024-12-05 09:50:29 +00:00
print("Part 1: ", part1)
2024-12-08 21:32:36 +00:00
part2 = 0
for update in incorrect_updates:
fix_update(update, rules)
middle = update[len(update)//2]
part2 += int(middle)
print("Part 2: ", part2)
2024-12-05 09:50:29 +00:00
if __name__ == "__main__":
import sys
infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt"
with open(infile) as f:
main(f.read())