← blog

Twelve Days · day 12 · both parts

Day 12: Christmas Tree Farm

the puzzle ↗ #aoc-2025#python

The last day, and a packing puzzle: the kind of problem that is hard in general, with an example that is hard in a small way. The interesting part is a search that can prove a “no”, and two checks that can make the search unnecessary.

The puzzle, in my words

The input lists a few present shapes, each drawn in a 3x3 box, and then a list of regions: a width, a height, and how many presents of each shape have to go in. Presents can be turned and mirrored but must sit on the grid without overlapping. Count the regions that can hold all of theirs.

The example has six shapes of 7 cells each and three regions. A 4x4 region takes two of the C-shaped presents, interlocked. A 12x5 region takes six presents. A second 12x5 region needs one more C, 49 cells in 60, and they don’t fit however you arrange them. So the answer is 2.

Part 1: packing the presents

Step 2’s search on the example’s three regions. Pale cells are free, a dot marks a cell left empty for good, and the counter is presents put down so far; after the first few moves of each region the frames skip ahead.

Step 1: the first version

Turning and mirroring a shape gives up to eight versions. Rotate a quarter turn four times, mirror, rotate four more times, and keep the distinct ones, each moved so its first cell (in reading order) is at (0, 0):

def orientations(shape):
    seen, out = set(), []
    cells = shape
    for flip in range(2):
        for _ in range(4):
            cells = {(c, -r) for r, c in cells}  # a quarter turn
            first = min(cells)
            norm = tuple(sorted((r - first[0], c - first[1]) for r, c in cells))
            if norm not in seen:
                seen.add(norm)
                out.append(list(norm))
        cells = {(r, -c) for r, c in cells}  # a mirror image
    return out

The example’s shapes have 8, 8, 2, 4, 4 and 2 of them: the S-like shape 2 looks the same after a half turn, and so on.

The first search puts the presents down one at a time. For each present it tries every orientation at every position that stays inside the region and doesn’t overlap what’s already there, and when a present has nowhere to go it backs up and moves the previous one. An area check first catches the obvious “no”.

def fits(w, h, counts, shapes):
    if sum(n * len(shapes[i]) for i, n in enumerate(counts)) > w * h:
        return False
    placements = []  # per shape: every way to put it in the region
    for shape in shapes:
        ways = []
        for cells in orientations(shape):
            for r in range(h):
                for c in range(w):
                    moved = {(r + dr, c + dc) for dr, dc in cells}
                    if all(0 <= y < h and 0 <= x < w for y, x in moved):
                        ways.append(moved)
        placements.append(ways)
    presents = [i for i, n in enumerate(counts) for _ in range(n)]
    used = set()

    def place(k, start):
        if k == len(presents):
            return True
        ways = placements[presents[k]]
        for j in range(start, len(ways)):
            if used.isdisjoint(ways[j]):
                used.update(ways[j])
                same_next = k + 1 < len(presents) and presents[k + 1] == presents[k]
                if place(k + 1, j + 1 if same_next else 0):
                    return True
                used.difference_update(ways[j])
        return False

    return place(0, 0)


def part1(text):
    shapes, regions = parse(text)
    return sum(fits(w, h, counts, shapes) for w, h, counts in regions)

The start argument matters more than it looks. Two presents of the same shape are interchangeable, so putting the first at A and the second at B is the same arrangement as the other way round. Without it, a region that can’t be filled is searched once for every ordering of its identical presents; with it, the second one only tries positions after the first’s.

parse reads the shapes as sets of (row, col) cells and each region as (w, h, counts); it’s in the solution file and not interesting.

This gets the example right, but slowly: about 5 seconds, nearly all of it on the third region. A “yes” can stop at the first arrangement that works; a “no” has to rule out every one.

Step 2: fill the first free cell

A better question to branch on: take the first free cell in reading order. Either it gets covered now, by the first cell of some present in some orientation, or it stays empty for good, because every later present starts after it. Branching this way doesn’t revisit the same arrangement through a different order of moves, and it gives a budget. The region has w * h - (cells the presents need) cells to spare. Each cell left empty spends one, and once they’re gone, every free cell must be covered.

The region is also now an int with one bit per cell. For each cell and each shape, the placements whose first cell lands there are precomputed as bitmasks, so “does it overlap” is board & mask:

def masks(w, h, shape):
    at = [[] for _ in range(w * h)]
    for cells in orientations(shape):
        for r in range(h):
            for c in range(w):
                if all(0 <= r + dr < h and 0 <= c + dc < w for dr, dc in cells):
                    at[r * w + c].append(sum(1 << ((r + dr) * w + c + dc) for dr, dc in cells))
    return at


def fits(w, h, counts, shapes):
    spare = w * h - sum(n * len(shapes[i]) for i, n in enumerate(counts))
    if spare < 0:
        return False
    at = [masks(w, h, shape) if n else None for shape, n in zip(shapes, counts)]
    left = list(counts)

    def fill(board, cell, spare, todo):
        if todo == 0:
            return True
        while True:
            while board >> cell & 1:  # cells already covered
                cell += 1
            for i, n in enumerate(left):
                if n:
                    for m in at[i][cell]:
                        if not board & m:
                            left[i] -= 1
                            found = fill(board | m, cell + 1, spare, todo - 1)
                            left[i] += 1
                            if found:
                                return True
            if spare == 0:
                return False
            cell, spare = cell + 1, spare - 1  # leave this cell empty

    return fill(0, 0, spare, sum(counts))

left holds counts per shape rather than a list of presents, so identical presents are one branch, not several. Leaving a cell empty is the last thing fill tries, and it’s written as a loop rather than a recursive call: the recursion is then one level per present placed, not per cell visited, which keeps a big region well inside Python’s default recursion limit of 1000.

On the example this takes about 2 seconds, still nearly all on the third region. Proving that one has no arrangement means about 1.5 million presents put down and taken up again. The clip above is this search. part1 is the same as in step 1, calling this fits.

Step 3: decide before searching

Two checks settle a region without a search, and both are certain:

  • If the presents need more cells than the region has, the answer is no.
  • Every shape fits in its 3x3 box. If the region has room for one box per present, side by side ((w // 3) * (h // 3) of them), the answer is yes.

Only a region between the two needs the search:

def fits(w, h, counts, shapes):
    if sum(n * len(shapes[i]) for i, n in enumerate(counts)) > w * h:
        return False
    if (w // 3) * (h // 3) >= sum(counts):
        return True
    return search(w, h, counts, shapes)  # step 2's fits

part1 is unchanged.

On the example this changes nothing: the 4x4 region has one 3x3 box for two presents, the 12x5 ones have four boxes for six and seven presents, and all three have enough area. All three go to the search, which is the point of the example: the third region has room to spare on paper, and only a search shows the presents can’t use it.

The real inputs are reported to be the opposite. Their regions are about 40 to 50 cells a side with a few hundred presents each, and write-ups say every one is settled by these two checks (the Scala Center’s and this one, which counts 1,000 regions). I couldn’t check that here. It’s also why the “count the area” solutions you’ll see work on real inputs but not on the example: “enough area” is not a yes, and the third example region is the counterexample.

On a generated input built that way (1,000 regions of 40 to 50 a side, the example’s shapes, half short of area and half with a box per present), step 3 takes about a millisecond. Step 2 takes about 40 seconds, and around 90% of that is building the placement tables: on the roomy regions I sampled, the fill never had to take a present back. Step 1 didn’t finish in nine minutes. And those are the easy regions for a search; one of that size that falls between the two checks could keep either search busy practically forever.

The last star

That was the last puzzle of the twelve. Day 12 has only this one part: its second star comes free once the other 23 are in.

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