-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.py
84 lines (60 loc) · 1.98 KB
/
day05.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
Advent of Code 2024, Day 5: Print Queue.
See: https://adventofcode.com/2024/day/5
"""
import functools
import sys
from typing import TextIO
def parse(file: TextIO):
rules_input, updates_input = file.read().split("\n\n")
rules = [
tuple(map(int, line.split("|", maxsplit=1)))
for line in rules_input.splitlines()
]
updates = [list(map(int, line.split(","))) for line in updates_input.splitlines()]
return rules, updates
def is_ordered(rules: list[tuple[int, int]], update: list[int]) -> bool:
for a, b in rules:
if a not in update or b not in update:
continue
if update.index(a) > update.index(b):
return False
return True
def compare(rules: list[tuple[int, int]], a: int, b: int) -> int:
for left, right in rules:
if a == left and b == right:
return -1
if a == right and b == left:
return 1
return 0
def part_one(file: TextIO) -> int:
"""
Solve part one of the puzzle.
"""
rules, updates = parse(file)
is_valid = functools.partial(is_ordered, rules)
valid_updates = filter(is_valid, updates)
return sum(update[len(update) // 2] for update in valid_updates)
def part_two(file: TextIO) -> int:
"""
Solve part two of the puzzle.
"""
rules, updates = parse(file)
is_valid = functools.partial(is_ordered, rules)
reorder_update = functools.cmp_to_key(functools.partial(compare, rules))
invalid_updates = list(filter(lambda u: not is_valid(u), updates))
return sum(
sorted(update, key=reorder_update)[len(update) // 2]
for update in invalid_updates
)
def main():
"""
The main entrypoint for the script.
"""
filename = sys.argv[0].replace(".py", ".txt")
with open(filename, encoding="utf-8") as file:
print("Part one:", part_one(file))
with open(filename, encoding="utf-8") as file:
print("Part two:", part_two(file))
if __name__ == "__main__":
main()