← blog

Twenty-Five Days · day 9 · both parts

Day 9: Disk Fragmenter

the puzzle ↗ #aoc-2024#python

A puzzle about defragmenting a disk. Part 1 is two pointers on a list, and part 2 is a search that is slow until you notice that the free spans only come in nine lengths.

The puzzle, in my words

The input is one long line of digits that take turns giving a file’s size and the size of the free gap after it (the last file has no gap). Files are numbered 0, 1, 2, … in the order they appear, so 12345 is the disk 0..111....22222 (a dot is a free block).

Part 1 compacts the disk one block at a time: take the last file block and put it in the leftmost free block, until there are no gaps between files. The answer is a checksum: each block’s position times the id of the file in it, summed (free blocks count 0). The example 2333133121414131402 is the 42-block disk 00...111...2...333.44.5555.6666.777.888899, which compacts to 0099811188827773336446555566 followed by free space, checksum 1928.

Part 1: one block at a time

Part 1 on the example. Gold marks the leftmost free block, red the last file block; red digits are blocks that moved.

Step 1: a block list and two pointers

Lay the disk out as a list with one entry per block: the file id, or None for free space. Then two pointers walk towards each other. The left one stops on a free block, the right one on a file block, and the file block moves across. When they meet, there are no gaps left.

def digits(text: str) -> list[int]:
    return [int(ch) for ch in text.strip()]


def blocks(text: str) -> list[int | None]:
    disk = []
    for i, n in enumerate(digits(text)):
        disk += [i // 2 if i % 2 == 0 else None] * n
    return disk


def checksum(disk: list[int | None]) -> int:
    return sum(pos * fid for pos, fid in enumerate(disk) if fid is not None)


def part1(text: str) -> int:
    disk = blocks(text)
    left, right = 0, len(disk) - 1
    while True:
        while left < right and disk[left] is not None:
            left += 1
        while left < right and disk[right] is None:
            right -= 1
        if left >= right:
            break
        disk[left], disk[right] = disk[right], None
    return checksum(disk)

Digits at even positions are files, so a file digit’s id is i // 2, and [x] * 0 is an empty list, so a gap of 0 adds nothing. Both pointers only ever move inwards, so the whole thing is one pass over the disk: about 8 ms on a generated map of 19,999 digits (10,000 files, about 95,000 blocks). The test for None uses is not None rather than truthiness on purpose: file 0 is falsy.

Step 2: whole runs at a time

The block list isn’t needed. Walk the map’s digits instead. A file digit is already in place: whatever of that file hasn’t been moved away stays where it is. A gap digit gets filled from the last file that still has blocks left, taking a whole run of blocks at once, or as much of the run as fits.

A run of n blocks of file fid starting at position p adds fid * (p + (p+1) + ... + (p+n-1)) to the checksum, and that sum is an arithmetic series: n*p + n*(n-1)/2.

def span_sum(fid: int, pos: int, length: int) -> int:
    return fid * (length * pos + length * (length - 1) // 2)


def part1(text: str) -> int:
    sizes = digits(text)
    files = sizes[0::2]  # files[fid] = blocks of that file not yet placed
    total, pos = 0, 0
    last = len(files) - 1  # the file the gaps are filled from
    for i, size in enumerate(sizes):
        fid = i // 2
        if fid > last:
            break
        if i % 2 == 0:
            total += span_sum(fid, pos, files[fid])
            pos += files[fid]
            files[fid] = 0
            continue
        while size and last > fid:
            take = min(size, files[last])
            total += span_sum(last, pos, take)
            pos += take
            size -= take
            files[last] -= take
            if files[last] == 0:
                last -= 1
    return total

n*(n-1) is a product of two consecutive integers, so it’s always even and // 2 is exact. The loop now turns once per run rather than once per block: about 3 ms on the same generated map. Not a speed-up that matters here, but thinking in runs rather than blocks is exactly what part 2 needs.

Part 2: whole files

Now files move whole. Each file is tried once, from the highest id down to 0, and goes into the leftmost gap that is big enough to hold all of it, as long as that gap is to its left. If there isn’t one, the file stays put. On the example only four files move (9, 7, 4 and 2), the disk ends as 00992111777.44.333....5555.6666.....8888.., and the checksum is 2858.

Part 2 on the example. Under the strip, each gap and its length; pink means too short for the file being moved, gold means it fits. The space a moved file leaves has no line: nothing moves into it again.

Step 1: scan a list of gaps

Keep the gaps as [position, length] pairs in disk order. For each file, highest id first, scan from the left for the first gap that is long enough, and stop once the gaps reach the file itself.

Two things keep this simple. A file moves into the front of its gap, so the gap only ever shrinks from the front: bump its position, cut its length. And the space a file leaves behind can be ignored, because every file still to be tried is to the left of it, and files only move left.

def layout(text: str) -> tuple[list[tuple[int, int]], list[list[int]]]:
    files, free = [], []
    pos = 0
    for i, n in enumerate(digits(text)):
        if i % 2 == 0:
            files.append((pos, n))
        elif n:
            free.append([pos, n])
        pos += n
    return files, free


def part2(text: str) -> int:
    files, free = layout(text)
    total = 0
    for fid in range(len(files) - 1, -1, -1):
        pos, length = files[fid]
        for span in free:
            if span[0] >= pos:
                break
            if span[1] >= length:
                pos = span[0]
                span[0] += length
                span[1] -= length
                break
        total += span_sum(fid, pos, length)
    return total

The checksum comes from span_sum again: a file ends up in one run, so it can be added the moment its place is known. The cost is the scan. With 10,000 files and nearly as many gaps, every file that can’t move looks at every gap to its left before giving up. That’s quadratic, and it shows: about 1.2 s on the generated map.

Step 2: one heap per gap length

A gap’s length is a single digit, so there are only nine lengths, 1 to 9 (gaps of 0 aren’t kept). Keep one min-heap of positions per length. The leftmost gap that fits a file of length L is then the smallest of the heads of heaps L to 9: at most nine looks instead of a scan.

Moving a file pops that gap from its heap. If the file didn’t fill it, the rest of the gap starts L blocks later and is L shorter, so it is pushed onto the heap for its new length.

import heapq


def part2(text: str) -> int:
    files, free = layout(text)
    heaps = [[] for _ in range(10)]
    for pos, length in free:
        heaps[length].append(pos)
    total = 0
    for fid in range(len(files) - 1, -1, -1):
        pos, length = files[fid]
        best, best_len = pos, 0
        for n in range(length, 10):
            if heaps[n] and heaps[n][0] < best:
                best, best_len = heaps[n][0], n
        if best_len:
            heapq.heappop(heaps[best_len])
            if best_len > length:
                heapq.heappush(heaps[best_len - length], best + length)
            pos = best
        total += span_sum(fid, pos, length)
    return total

Three details carry the correctness. It has to be the smallest position across all the heaps that fit, not the first heap that fits: on 13222 (the disk 0...11..22), file 2 needs 2 blocks and must take the 3-block gap at position 1, not the exact 2-block gap at position 6. Starting best at the file’s own position means a gap is only taken if it is left of the file. And the heaps need no heapify: positions are appended in disk order, so each list is sorted, and a sorted list already satisfies heapq’s heap invariant (every parent is no bigger than its children).

On the generated map this takes about 10 ms instead of 1.2 s.

Both steps lean on files being at least one block long. A file of length 0 would let two gaps touch and act as one longer gap, possibly longer than 9, which neither the gap list nor the heaps would see. The example has no zero-length files, and whether real inputs ever do couldn’t be checked here, so this is an assumption of the code. The tests compare both steps against a block-by-block version of the rule on 500 random maps without zero-length files, plus a case where the leftmost gap beats a tighter one and a case where the only gap that fits is to the file’s right.

All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.