← blog

Twenty-Five Days · day 4 · both parts

Day 4: Ceres Search

the puzzle ↗ #aoc-2024#python

A word search with one word in it. Part 1 is the usual grid walk in eight directions, and the interesting part is seeing that you don’t need directions at all: cut the grid into lines and let str.count do it. Part 2 is smaller than it looks, a check of the four corners around each A.

The puzzle, in my words

The input is a rectangle of letters. Count every XMAS in it, written in any of the eight directions: across, down, diagonally, and any of those backwards. Occurrences can overlap and share letters.

The example is ten rows of ten letters, and XMAS appears 18 times in it.

Part 1: XMAS in eight directions

Part 1 on the example. The first three X’s play slowly, the rest faster. Right: the words found so far, by direction.

Step 1: the first version

From every cell, try each of the eight directions: walk four letters, checking the position is inside the grid before reading it, and stop at the first letter that isn’t the next one of XMAS.

DIRECTIONS = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]


def part1(text: str) -> int:
    rows = text.split()
    height, width = len(rows), len(rows[0])
    count = 0
    for r in range(height):
        for c in range(width):
            for dr, dc in DIRECTIONS:
                found = True
                for k in range(4):
                    rr, cc = r + dr * k, c + dc * k
                    if rr < 0 or rr >= height or cc < 0 or cc >= width:
                        found = False
                        break
                    if rows[rr][cc] != "XMAS"[k]:
                        found = False
                        break
                if found:
                    count += 1
    return count

It’s correct and it isn’t slow: on a generated 140x140 grid (the size of the real inputs, going by public solutions) it takes about 20 ms. Most of the code is bookkeeping, though, and the bounds check is the part that is easy to get wrong.

Step 2: a dict of complex positions

Store the grid as a dict from position to letter, with the position as a complex number, column + row * 1j. A direction is then a complex number too, and stepping is addition. Reading off the edge is a missing key, so grid.get returns None, which is never equal to a letter: the bounds check disappears.

def grid_of(text: str) -> dict[complex, str]:
    return {c + r * 1j: ch for r, line in enumerate(text.split()) for c, ch in enumerate(line)}


STEPS = [complex(dc, dr) for dr, dc in DIRECTIONS]


def part1(text: str) -> int:
    grid = grid_of(text)
    return sum(
        all(grid.get(p + d * k) == letter for k, letter in enumerate("MAS", start=1))
        for p, ch in grid.items()
        if ch == "X"
        for d in STEPS
    )

Only an X can start the word, so the generator skips the other cells, and all() stops at the first letter that doesn’t match, as the inner break did. sum adds up the Trues, each of which counts as 1.

The keys are complex numbers with float parts (3 + 2j is complex(3.0, 2.0)), but small whole numbers are exact as floats, so adding steps lands on exactly the same keys. About 16 ms on the same grid: tidier, not faster.

Step 3: lines, not directions

Eight directions are really four kinds of line, rows, columns, and the two diagonals, each read forwards and backwards. So turn the grid into strings, one per line, and count XMAS and its reverse SAMX in each.

Columns are zip(*rows). On a diagonal running down and to the right, column - row is the same for every cell; on one running down and to the left, column + row is. That makes them easy to collect in two defaultdict(str)s, adding each letter in reading order:

from collections import defaultdict


def part1(text: str) -> int:
    rows = text.split()
    lines = rows + ["".join(col) for col in zip(*rows)]
    diagonal, anti = defaultdict(str), defaultdict(str)
    for r, row in enumerate(rows):
        for c, ch in enumerate(row):
            diagonal[c - r] += ch
            anti[c + r] += ch
    lines += [*diagonal.values(), *anti.values()]
    return sum(line.count("XMAS") + line.count("SAMX") for line in lines)

One thing to check: str.count counts non-overlapping occurrences, and the puzzle allows overlaps. That’s safe here. Two XMAS can’t overlap, because no start of the word is also an end of it (X against S, XM against AS, XMA against MAS). An XMAS and a SAMX can share letters, as in XMASAMX, but they’re counted by separate calls. The tests check this step against the other two on 300 random grids made only of the letters XMAS, where overlaps are everywhere.

The searching now happens inside str.count, which is written in C: about 3.5 ms on the generated grid, six times faster than step 1.

Part 2: X-MAS

Part 2 says the word was never XMAS. The task is to find two MAS in the shape of an X, crossing on the A: each diagonal of the 3x3 square around an A must read MAS, forwards or backwards. That gives four shapes, such as

M.S
.A.
M.S

A + of a horizontal and a vertical MAS doesn’t count. The example has 9.

Part 2 on the same example: only the A’s, and only their diagonals. Right: how many crosses of each shape.

Step 1: look round every A

No walking in directions this time. Every A that isn’t on the border is a possible centre, and each of its diagonals needs an M at one end and an S at the other:

def part2(text: str) -> int:
    rows = text.split()
    count = 0
    for r in range(1, len(rows) - 1):
        for c in range(1, len(rows[0]) - 1):
            if rows[r][c] != "A":
                continue
            a, b = rows[r - 1][c - 1], rows[r + 1][c + 1]
            d, e = rows[r - 1][c + 1], rows[r + 1][c - 1]
            first = (a == "M" and b == "S") or (a == "S" and b == "M")
            second = (d == "M" and e == "S") or (d == "S" and e == "M")
            if first and second:
                count += 1
    return count

The ranges start at 1 and stop one short of the end, so the four corners are always inside the grid. About 1 ms on the generated grid.

Step 2: the diagonals as sets

“An M at one end and an S at the other” is a set comparison: {a, b} == {"M", "S"} is true for MS and SM, and false for MM or SS, which make a one-element set, and for anything with another letter in it.

def part2(text: str) -> int:
    rows = text.split()
    ms = {"M", "S"}
    return sum(
        rows[r][c] == "A"
        and {rows[r - 1][c - 1], rows[r + 1][c + 1]} == ms
        and {rows[r - 1][c + 1], rows[r + 1][c - 1]} == ms
        for r in range(1, len(rows) - 1)
        for c in range(1, len(rows[0]) - 1)
    )

Same speed, half the lines, and the rule reads the way the puzzle states it. The tests also run both steps against a third method on the random grids: a 3x3 window slid over the grid, its corners and centre matched against the four shapes.

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