Skip to content

Commit 3a29202

Browse files
committed
Add solution to 2024-12-09
1 parent 8370345 commit 3a29202

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

2024/day09/solutions.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
with open("input") as f:
2+
ns = list(map(int, f.read().strip()))
3+
4+
# Part 1
5+
disk = []
6+
for i, n in enumerate(ns):
7+
disk += [None if i % 2 else i // 2] * n
8+
9+
head = ns[0]
10+
while head < len(disk):
11+
if disk[head]:
12+
head += 1
13+
elif num := disk.pop():
14+
disk[head] = num
15+
16+
print(sum(i * n for i, n in enumerate(disk)))
17+
18+
# Part 2
19+
blocks = []
20+
head = 0
21+
for i, n in enumerate(ns):
22+
if not i % 2:
23+
blocks.append((i // 2, head, head + n))
24+
head += n
25+
26+
for to_move in range(i // 2, -1, -1):
27+
block = next(b for b in blocks if b[0] == to_move)
28+
_, start, end = block
29+
space_needed = end - start
30+
for i, ((_, _, end1), (_, start2, _)) in enumerate(zip(blocks, blocks[1:])):
31+
if end1 == end:
32+
break
33+
if start2 - end1 >= space_needed:
34+
blocks.insert(i + 1, (to_move, end1, end1 + space_needed))
35+
blocks.remove(block)
36+
break
37+
38+
print(
39+
sum(
40+
block_id * index
41+
for block_id, start, end in blocks
42+
for index in range(start, end)
43+
)
44+
)

0 commit comments

Comments
 (0)