-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday5.py
87 lines (59 loc) · 1.71 KB
/
day5.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
85
86
87
# Advent of Code 2024, Day 5
# (c) blu3r4y
from aocd.models import Puzzle
from funcy import print_calls, print_durations
@print_calls
@print_durations(unit="ms")
def part1(data):
rules, books = data
result = 0
for pages in books:
if satisfies(pages, rules):
result += middle(pages)
return result
@print_calls
@print_durations(unit="ms")
def part2(data):
rules, books = data
incorrect = set()
for i, pages in enumerate(books):
while not satisfies(pages, rules):
incorrect.add(i)
fixup(pages, rules)
result = 0
for i in incorrect:
result += middle(books[i])
return result
def satisfies(num, rules):
for a, b in rules:
if a not in num or b not in num:
continue
apos, bpos = num.index(a), num.index(b)
if apos > bpos:
return False
return True
def middle(num):
return num[len(num) // 2]
def fixup(num, rules):
for a, b in rules:
if a not in num or b not in num:
continue
apos, bpos = num.index(a), num.index(b)
if apos > bpos:
num[apos], num[bpos] = num[bpos], num[apos]
def load(data):
rules, books = [], []
sectiona, sectionb = data.split("\n\n")
for line in sectiona.splitlines():
rules.append(tuple(map(int, line.split("|"))))
for line in sectionb.splitlines():
books.append(list(map(int, line.split(","))))
return rules, books
if __name__ == "__main__":
puzzle = Puzzle(year=2024, day=5)
ans1 = part1(load(puzzle.input_data))
assert ans1 == 6384
puzzle.answer_a = ans1
ans2 = part2(load(puzzle.input_data))
assert ans2 == 5353
puzzle.answer_b = ans2