← blog

Twenty-Five Days · day 3 · both parts

Day 3: Mull It Over

the puzzle ↗ #aoc-2024#python

A regular-expression day. Part 1 is what re was made for, and the interesting part is part 2, where the same problem has three reasonable shapes and one of them has a trap in it.

The puzzle, in my words

The input is a long string of junk with some instructions hidden in it. A real instruction is exactly mul(X,Y), where X and Y have one to three digits and nothing else sits between the brackets: no spaces, no other brackets. Add up X times Y over all the real ones.

In the example, xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)), four are real: 2·4 + 5·5 + 11·8 + 8·5 = 161. mul[3,7] has the wrong brackets and mul(32,64] never closes properly.

Part 1: find the real muls

Part 1 on the example. Pink is the scanner reading ahead, gold a real mul, red the character that breaks a near miss.

Step 1: the first version

Jump to each mul( with str.find, then check by hand that one to three digits, a comma, one to three digits and a ) follow:

DIGITS = "0123456789"


def mul_at(text: str, i: int) -> int | None:
    """X*Y if a real mul(X,Y) starts at text[i], else None."""
    if not text.startswith("mul(", i):
        return None
    j = i + 4
    numbers = []
    for closing in ",)":
        start = j
        while j < len(text) and j - start < 3 and text[j] in DIGITS:
            j += 1
        if j == start or not text.startswith(closing, j):
            return None  # no digits, more than 3, or the wrong character after them
        numbers.append(int(text[start:j]))
        j += 1
    return numbers[0] * numbers[1]


def part1(text: str) -> int:
    total = 0
    i = text.find("mul(")
    while i != -1:
        product = mul_at(text, i)
        if product is not None:
            total += product
        i = text.find("mul(", i + 1)
    return total

startswith takes a start position, so it checks for a word at i without slicing a copy of the text. The digits are tested against "0123456789" rather than with str.isdigit(), which also says yes to characters such as ² that int() then refuses. The puzzle’s memory is plain ASCII, so it wouldn’t matter here.

Step 2: say it as a regular expression

The rule is a pattern, so write the pattern. \d{1,3} is one to three digits, the round brackets are escaped because they mean grouping in a regex, and the two unescaped pairs capture the numbers:

import re

MUL = re.compile(r"mul\((\d{1,3}),(\d{1,3})\)")


def part1(text: str) -> int:
    return sum(int(x) * int(y) for x, y in MUL.findall(text))

With two groups in the pattern, findall returns a list of (x, y) string pairs, one per match, found left to right without overlapping. A near miss like mul(32,64] simply fails to match at that position and the search moves on, which is what the scanner did by hand. One small difference: in a str pattern \d matches any Unicode decimal digit, such as ٣, not only 0 to 9. int() accepts all of those, so nothing breaks, and the puzzle’s ASCII memory never has them.

Part 2: do() and don’t()

Two more instructions now: don't() switches off the muls after it, and do() switches them back on. The latest one wins, and the memory starts switched on. Part 2 has its own example, xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)): mul(5,5) and mul(11,8) come after the don't() and are skipped, and the undo() near the end contains a do(), which switches things back on in time for mul(8,5). That leaves 2·4 + 8·5 = 48.

Part 2 on its own example. Green is do(), red don’t(); a mul read while the switch is OFF gets a grey box and is skipped.

Step 1: the scanner with a switch

Walk every position. A do() or don't() flips a flag, and a mul only counts while the flag is on:

def part2(text: str) -> int:
    total, enabled = 0, True
    for i in range(len(text)):
        if text.startswith("do()", i):
            enabled = True
        elif text.startswith("don't()", i):
            enabled = False
        elif enabled:
            product = mul_at(text, i)
            if product is not None:
                total += product
    return total

Step 2: cut the text instead

Part 1 already sums the muls in a string, so the switches can be handled by cutting the text into the stretches that are on. Everything before the first don't() is on. Every piece after a don't() starts off and is on from its first do(), which str.partition finds (it returns an empty separator when there isn’t one):

def part2(text: str) -> int:
    first, *rest = text.split("don't()")
    total = part1(first)
    for piece in rest:
        _, found, after = piece.partition("do()")
        if found:
            total += part1(after)
    return total

The trap is in the obvious next move: joining the pieces that are on and calling part1 once. In mul(1,don't()do()2) there is no real mul, but the two pieces that are on, mul(1, and 2), would join into mul(1,2). Summing each piece on its own avoids that. Cutting never splits a real mul, because a real mul has only digits and a comma between its brackets, so it can’t contain do() or don't().

Step 3: one pattern for all three instructions

Back to one pass. A regex alternation matches whichever instruction comes next, in the order they appear in the text, and the switch is a flag again:

INSTRUCTION = re.compile(r"mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)")


def part2(text: str) -> int:
    total, enabled = 0, True
    for m in INSTRUCTION.finditer(text):
        if m[0] == "do()":
            enabled = True
        elif m[0] == "don't()":
            enabled = False
        elif enabled:
            total += int(m[1]) * int(m[2])
    return total

m[0] is the whole match and m[1], m[2] the groups; for a do() or don't() match the groups are None, but they’re only read for a mul. This is the version I’d keep: the rule reads straight off the code, and there’s no piece-joining to get wrong.

On a generated input of six lines of 3,000 characters with about 600 real muls, the hand-written scanners take about 0.7 ms (part 1) and 1.4 ms (part 2), and the regex versions 0.1 to 0.25 ms. The split happens to be the quickest of the three part 2 versions on that input. None of it matters at this size; the steps are about clarity rather than speed. The tests run all three part 2 versions, and both part 1 versions, on 300 generated strings full of near misses, stray do(, undo() and four-digit numbers, and check that they agree.

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