← blog

Twenty-Five Days · day 25 · both parts

Day 25: Code Chronicle

the puzzle ↗ #aoc-2024#python

The last day, and a gentle one: there is nothing to search and nothing to optimise beyond trying every pair. The interesting part is seeing that the heights the puzzle talks about can be skipped altogether.

The puzzle, in my words

The input is a pile of small pictures, 5 columns by 7 rows. A lock has its top row filled and pins hanging down from it; a key has its bottom row filled and teeth rising from it. Read each column’s height (filled cells, not counting the full row) and a lock becomes five numbers, say 0,5,3,4,3, and so does a key, say 5,0,2,1,3. There are five rows between the two full rows, so a key fits a lock when no column’s two heights add up to more than 5. Count the lock and key pairs that fit.

That first pair doesn’t: the last column needs 3 + 3 = 6 rows. The example has two locks and three keys, six pairs, and 3 of them fit.

Part 1: every key in every lock

The example’s two locks and three keys. Middle: the pair together, red where both fill a cell. Below it: each column’s lock height plus key height, red when it is more than 5.

Step 1: the first version

Split the input on blank lines, sort each picture into locks or keys by its top row, and count the # in every column, less one for the full row. Then try every key in every lock:

def part1(text: str) -> int:
    locks = []
    keys = []
    for block in text.strip().split("\n\n"):
        rows = block.split("\n")
        heights = []
        for c in range(5):
            filled = 0
            for r in range(7):
                if rows[r][c] == "#":
                    filled += 1
            heights.append(filled - 1)
        if rows[0] == "#####":
            locks.append(heights)
        else:
            keys.append(heights)
    count = 0
    for lock in locks:
        for key in keys:
            fits = True
            for c in range(5):
                if lock[c] + key[c] > 5:
                    fits = False
            if fits:
                count += 1
    return count

Every pair has to be tried, and that’s fine at this size. A thread on the puzzle reports 250 locks and 250 keys in a real input, 62,500 pairs; I couldn’t check that here. On a generated input of that size this takes about 11 ms.

Step 2: zip, product and all

The same method, in fewer lines. zip(*rows) turns the rows into columns, so a column’s height is col.count("#") - 1. itertools.product(locks, keys) gives every pair, and all() over the zipped heights asks whether every column fits. sum() counts the Trues, since bool is a subclass of int and True is 1:

from itertools import product


def heights(block: str) -> tuple[bool, list[int]]:
    rows = block.split()
    return rows[0] == "#####", [col.count("#") - 1 for col in zip(*rows)]


def part1(text: str) -> int:
    locks, keys = [], []
    for block in text.strip().split("\n\n"):
        is_lock, h = heights(block)
        (locks if is_lock else keys).append(h)
    return sum(all(a + b <= 5 for a, b in zip(lock, key)) for lock, key in product(locks, keys))

all() stops at the first column that doesn’t fit, which step 1 didn’t bother to do. Even so, this one is shorter, not faster: about 27 ms on the same generated input against step 1’s 11, because each of the 62,500 pairs now builds a generator and calls a function, and that costs more than five additions in a plain loop.

Step 3: no heights at all

Look at a single column. The lock fills it from the top down to row a (its height), the key from the bottom up to row 6 - b. Those two runs share a cell exactly when a >= 6 - b, that is when a + b > 5. So “the heights add up to more than 5” is the same as “some cell is # in both pictures”, and the heights were never needed.

Make each picture a number with one bit per cell: join its 35 characters, write # as 1 and . as 0, and read the result as binary. Then a pair fits when the two numbers share no bit, lock & key == 0:

from itertools import product


def mask(block: str) -> int:
    return int(block.replace("\n", "").replace("#", "1").replace(".", "0"), 2)


def part1(text: str) -> int:
    locks, keys = [], []
    for block in text.strip().split("\n\n"):
        (locks if block[0] == "#" else keys).append(mask(block))
    return sum(not lock & key for lock, key in product(locks, keys))

not lock & key reads as not (lock & key), because not binds more loosely than &. 35 bits is nothing for a Python int. The work per pair is now a single & instead of five additions, and the generated input takes about 2.4 ms.

The same idea removes the sorting too. Two locks always share their full top row and two keys their full bottom row, so neither kind of pair ever fits; counting every pair of pictures that shares no cell, with itertools.combinations, gives the same answer without asking which is which. It checks twice as many pairs, though (about 5.4 ms), so the version above keeps the sort. The tests check that the two agree on 200 generated inputs, and that all three steps agree on 300 more.

The last star

That was the last puzzle of the twenty-five. Day 25 has only this one part: its second star comes free once the other 49 are in.

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