Skip to content

Commit 83a34f0

Browse files
committed
Add solution to 2024-12-05
1 parent 505d597 commit 83a34f0

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

2024/day05/solutions.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import networkx as nx
2+
3+
with open("input") as f:
4+
gs = f.read().strip().split("\n\n")
5+
6+
rules = [tuple(map(int, l.split("|"))) for l in gs[0].split("\n")]
7+
updates = [tuple(map(int, l.split(","))) for l in gs[1].split("\n")]
8+
9+
unsorted_updates = {
10+
update
11+
for update in updates
12+
if any(
13+
a in update and b in update and update.index(a) > update.index(b)
14+
for a, b in rules
15+
)
16+
}
17+
18+
# Part 1
19+
print(
20+
sum(
21+
update[len(update) // 2] for update in updates if update not in unsorted_updates
22+
)
23+
)
24+
25+
# Part 2
26+
sorted_updates = [
27+
list(
28+
nx.topological_sort(
29+
nx.DiGraph((a, b) for a, b in rules if a in update and b in update)
30+
)
31+
)
32+
for update in unsorted_updates
33+
]
34+
35+
print(sum(update[len(update) // 2] for update in sorted_updates))

0 commit comments

Comments
 (0)