← blog

Twenty-Five Days · day 19 · both parts

Day 19: Linen Layout

the puzzle ↗ #aoc-2024#python

A string-splitting puzzle where the obvious recursion is correct and hopeless, and the fix is one decorator. Part 2 then asks a question that only the fixed version can answer at all.

The puzzle, in my words

There’s a list of towel patterns, short strings of the letters w u b r g (stripe colours), and a list of designs, longer strings of the same letters. A design can be made if it can be cut into pieces that are all towel patterns, using any pattern as often as you like. Count the designs that can be made.

With the patterns r, wr, b, g, bwu, rb, gb, br, the design gbbr can be cut as gb + br, rrbgbr as r + rb + g + br, but ubwu can’t be made at all: no pattern starts with u. Six of the example’s eight designs can be made.

Part 1: which designs can be made

Part 1 on the example, following step 3. Pink: an ending the cache already knew, so no search.

Step 1: the first version

A design can be made if some pattern starts it and the rest can be made too. The empty design is made with no towels at all, which ends the recursion.

def parse(text: str) -> tuple[list[str], list[str]]:
    top, bottom = text.strip().split("\n\n")
    return top.split(", "), bottom.split()


def part1(text: str) -> int:
    patterns, designs = parse(text)

    def possible(design: str) -> bool:
        if design == "":
            return True
        for p in patterns:
            if design.startswith(p) and possible(design[len(p) :]):
                return True
        return False

    return sum(possible(d) for d in designs)

This is correct, and on the example it’s instant. The trouble is a design that fails near its end. Before it can say no, it has to try every way of cutting everything before the failure, and with a few hundred patterns, including the short ones, the number of ways to cut a string grows exponentially with its length.

To see it, I built a puzzle-sized input (450 patterns of 1 to 8 stripes, 400 designs of 20 to 60 stripes, 61 of which can’t be made and fail only at their last one or two stripes; the shape is my generator’s, not checked against a real input) and timed one failing design as its makeable part grows:

makeable stripestime
2022 ms
300.57 s
406.7 s
45more than 20 s

Every five stripes cost three to four times as much. On the whole generated input it didn’t finish in a minute. One write-up reports the same on a real input: a plain recursive search that ran for minutes without an answer.

Step 2: it’s a regular expression

“One or more patterns, end to end, and nothing else” is exactly what a regex says. Join the patterns into an alternation, repeat it, and ask for a match of the whole design:

import re


def part1(text: str) -> int:
    patterns, designs = parse(text)
    towels = re.compile("(?:" + "|".join(patterns) + ")*")
    return sum(towels.fullmatch(d) is not None for d in designs)

fullmatch (Python 3.4+) only succeeds if the match covers the whole string, so there’s no need for ^ and $. It’s tidy, and it is faster: on the same failing designs it took about a seventh of the time of step 1 at every length (0.97 s at 40 stripes, 4.1 s at 45). But it grows at the same rate: like step 1, when the rest won’t match it has to back up and try the other alternatives, and on a design that fails late that’s nearly all of the work. It didn’t finish the generated input in a minute either. A regex is the right tool when it rarely has to back up; here backing up is the whole job.

Step 3: remember the answers

Watch step 1 work and it keeps asking the same question: can this ending be made? A design of n stripes only has n + 1 endings, so the exponential number of calls is really a small number of questions asked over and over. functools.cache (Python 3.9+) remembers each answer:

from functools import cache


def part1(text: str) -> int:
    patterns, designs = parse(text)

    @cache
    def possible(design: str) -> bool:
        if design == "":
            return True
        return any(design.startswith(p) and possible(design[len(p) :]) for p in patterns)

    return sum(possible(d) for d in designs)

The cache is keyed by the ending itself, a string, and it lives for one call of part1, so designs that end the same way share the work. The animation shows that on the example: bggr finds that its last r is already known to work, and in bbrgwb the ending gwb comes up twice and fails instantly the second time. On the generated input this takes about 60 ms.

Part 2: how many ways

Now count, for each design, the number of different ways to cut it into patterns, and add them all up. In the example gbbr has four (g b b r, g b br, gb b r, gb br), and the eight designs give 2, 1, 4, 6, 0, 1, 2 and 0: 16.

Part 2 on the example, following step 2: under each gap, the number of ways to make everything to its left.

Step 1: count instead of check

The number of ways to make a design is the sum, over the patterns that start it, of the number of ways to make the rest; the empty design can be made in exactly one way. That’s step 3 of part 1 with sum where any was:

def part2(text: str) -> int:
    patterns, designs = parse(text)

    @cache
    def ways(design: str) -> int:
        if design == "":
            return 1
        return sum(ways(design[len(p) :]) for p in patterns if design.startswith(p))

    return sum(ways(d) for d in designs)

Here the cache isn’t an optimisation but the only reason this can work. On the generated input one 60-stripe design can be made in about 5.2 billion ways, and a search that found them one at a time would need that many steps for one design. With the cache, each ending’s count is worked out once from the counts of shorter endings, and the ways themselves are never listed. Python’s integers have no fixed size, so the totals can’t overflow (one write-up in a language with fixed-size integers needed 64-bit ones). About 160 ms on the generated input.

Step 2: build it up from the left

The same idea works forwards and without recursion. Every way to make the first j stripes ends with one towel, design[i:j], after some way to make the first i. So start with one way to make nothing, walk along the design, and at each position pass its count on to every position a towel reaches from there:

def ways(design: str, towels: set[str], longest: int) -> list[int]:
    counts = [1] + [0] * len(design)
    for i in range(len(design)):
        if counts[i]:
            for j in range(i + 1, min(i + longest, len(design)) + 1):
                if design[i:j] in towels:
                    counts[j] += counts[i]
    return counts


def part2(text: str) -> int:
    patterns, designs = parse(text)
    towels, longest = set(patterns), max(map(len, patterns))
    return sum(ways(d, towels, longest)[-1] for d in designs)

counts[i] is the number of ways to make the first i stripes, which is the number under each gap in the animation. For rrbgbr they come out as 1, 1, 1, 2, 2, 4, 6.

There’s a second change hidden in here. Step 1 tries every pattern with startswith at every ending: 450 tries. This one looks at the next 1 to 8 stripes and checks each in a set, so at most 8 hash lookups. It takes about 8 ms on the generated input instead of 160, and I checked where that comes from: the cached recursion with the set lookups instead takes about 12 ms, while this loop with startswith over every pattern takes about 136 ms. So it’s the lookups, not the missing recursion, and they’re also why part 1’s step 3 (60 ms) is slower than this whole count.

It also answers part 1: a design can be made exactly when its last count isn’t 0. The tests check that, and check every step against a version that lists all the ways one by one, on 400 small random cases.

All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own. The timings were taken on a busy machine, so read them as rough.