-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday5.py
More file actions
36 lines (28 loc) · 1.05 KB
/
day5.py
File metadata and controls
36 lines (28 loc) · 1.05 KB
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
import networkx as nx
from lib.input import get_input
lines = get_input(2024, 5).split("\n\n")
rules = [tuple(map(int, line.split("|"))) for line in lines[0].splitlines()]
updates = [list(map(int, line.split(","))) for line in lines[1].splitlines()]
invalid_updates = updates.copy()
def part1():
res = 0
for update in updates:
for rule in rules:
if rule[0] in update and rule[1] in update and update.index(rule[0]) > update.index(rule[1]):
break
else:
invalid_updates.remove(update) # for part 2
res += update[len(update) // 2]
return res
def part2():
res = 0
for update in invalid_updates:
matchin_rules = []
for rule in rules:
if rule[0] in update and rule[1] in update:
matchin_rules.append(rule)
graph = nx.DiGraph()
graph.add_edges_from(matchin_rules)
sorted_updates = list(nx.topological_sort(graph))
res += sorted_updates[len(sorted_updates) // 2]
return res