Skip to content

Commit

Permalink
Day 9: Disk Defragmenter
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient committed Dec 9, 2024
1 parent 7c02626 commit 9c1fa8e
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ Development occurs in language-specific directories:
|[Day6.hs](hs/src/Day6.hs)|[Day6.kt](kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day6.kt)|[day6.py](py/aoc2024/day6.py)|[day6.rs](rs/src/day6.rs)|
|[Day7.hs](hs/src/Day7.hs)|[Day7.kt](kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day7.kt)|[day7.py](py/aoc2024/day7.py)|[day7.rs](rs/src/day7.rs)|
|[Day8.hs](hs/src/Day8.hs)|[Day8.kt](kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day8.kt)|[day8.py](py/aoc2024/day8.py)|[day8.rs](rs/src/day8.rs)|
|[Day9.hs](hs/src/Day9.hs)|[Day9.kt](kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day9.kt)|||
|[Day9.hs](hs/src/Day9.hs)|[Day9.kt](kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day9.kt)|[day9.py](py/aoc2024/day9.py)||
65 changes: 65 additions & 0 deletions py/aoc2024/day9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
Day 9: Disk Defragmenter
"""

from itertools import accumulate

SAMPLE_INPUT = """
2333133121414131402
"""


def _rangesum(start: int, size: int) -> int:
return (2 * start + size - 1) * size // 2


def part1(data: str) -> int:
"""
>>> part1(SAMPLE_INPUT)
1928
"""
chunks = [int(c) for c in data if c.isdigit()]
total, offset, i, j = 0, 0, 0, len(chunks) - 1
while i <= j:
if not i % 2:
size = chunks[i]
total += i // 2 * _rangesum(offset, size)
offset += size
i += 1
elif not j % 2:
size = min(chunks[i], chunks[j])
total += j // 2 * _rangesum(offset, size)
offset += size
chunks[i] -= size
if chunks[i] <= 0:
i += 1
chunks[j] -= size
if chunks[j] <= 0:
j -= 1
else:
j -= 1
return total


def part2(data: str) -> int:
"""
>>> part2(SAMPLE_INPUT)
2858
"""
chunks = [int(c) for c in data if c.isdigit()]
offsets = list(accumulate(chunks, initial=0))
total = 0
for i in range(len(chunks) - 1 & ~1, -1, -2):
size = chunks[i]
offset = offsets[i]
for j in range(1, i, 2):
if chunks[j] >= size:
offset = offsets[j]
offsets[j] += size
chunks[j] -= size
break
total += i // 2 * _rangesum(offset, size)
return total


parts = (part1, part2)
1 change: 1 addition & 0 deletions py/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ day5 = "aoc2024.day5:parts"
day6 = "aoc2024.day6:parts"
day7 = "aoc2024.day7:parts"
day8 = "aoc2024.day8:parts"
day9 = "aoc2024.day9:parts"

[build-system]
requires = ["poetry-core"]
Expand Down

0 comments on commit 9c1fa8e

Please sign in to comment.