← blog

Twenty-Five Days · day 8 · both parts

Day 8: Resonant Collinearity

the puzzle ↗ #aoc-2024#python

A grid day with very little grid in it. Part 1 is one line of arithmetic per pair of antennas. Part 2 extends that point to a whole line, and the one detail worth getting right is how big a step to take along it.

The puzzle, in my words

A map shows antennas, each marked with a letter or digit for its frequency. Two antennas on the same frequency make two antinodes: go from one antenna to the other, then keep going the same distance again, and do the same in the other direction. Count the cells on the map that get an antinode. Antinodes that land off the map don’t count, and two that land on the same cell count once. An antinode can sit on an antenna’s cell.

The example has four 0 antennas and three A antennas on a 12x12 map. Its 6 + 3 pairs make 18 antinodes: 3 fall off the map and 1 lands where another already is, which leaves 14.

Part 1: two beyond every pair

Part 1 on the example. Each pair throws a line past each of its antennas; gold cells are antinodes, and the count is on the right.

Step 1: the first version

Group the antennas by frequency, then take every ordered pair (i, j) in a group. The antinode on i’s side is i plus the step from j to i, which is 2 * i - j in each coordinate. The pair in the other order gives the one on j’s side.

def part1(text: str) -> int:
    lines = text.split()
    height, width = len(lines), len(lines[0])
    antennas = {}
    for r, line in enumerate(lines):
        for c, ch in enumerate(line):
            if ch != ".":
                antennas.setdefault(ch, []).append((r, c))
    antinodes = set()
    for positions in antennas.values():
        for i in range(len(positions)):
            for j in range(len(positions)):
                if i == j:
                    continue
                r1, c1 = positions[i]
                r2, c2 = positions[j]
                r, c = 2 * r1 - r2, 2 * c1 - c2
                if 0 <= r < height and 0 <= c < width:
                    antinodes.add((r, c))
    return len(antinodes)

A literal reading of the rule (“one antenna twice as far away as the other”) would also allow two points between the antennas, a third of the way along, whenever the gap divides by 3. The puzzle says two antinodes per pair, one on each side, and the example’s 14 only counts those, so the in-between points are out.

Step 2: complex numbers, permutations and a set

Write each cell as a complex number, column + row × 1j. Then 2 * a - b is one expression, itertools.permutations(group, 2) gives the ordered pairs without indices or the i == j check, and staying on the map is membership in the set of all cells, so the bounds check becomes a set intersection:

from collections import defaultdict
from itertools import permutations


def parse(text: str) -> tuple[dict[str, list[complex]], set[complex]]:
    antennas = defaultdict(list)
    cells = set()
    for r, line in enumerate(text.split()):
        for c, ch in enumerate(line):
            cells.add(complex(c, r))
            if ch != ".":
                antennas[ch].append(complex(c, r))
    return antennas, cells


def part1(text: str) -> int:
    antennas, cells = parse(text)
    antinodes = {2 * a - b for group in antennas.values() for a, b in permutations(group, 2)}
    return len(antinodes & cells)

This one is shorter, not faster. On a generated 50x50 map with 40 frequencies of 4 antennas each, step 1 takes about 0.1 ms and step 2 about 0.3 ms, because building a set of 2,500 cells costs more than four comparisons per antinode. At these sizes neither matters.

Part 2: the whole line

Now the distance doesn’t matter: any cell that lies exactly on the line through two same-frequency antennas is an antinode. That includes the antennas themselves, as long as they have a partner. The example goes from 14 to 34.

Part 2 on the same map: every pair’s whole line, walked one gap at a time in both directions.

Step 1: check every cell

Read the rule literally. A cell (r, c) is on the line through (r1, c1) and (r2, c2) when the cross product of the two directions is zero, (r - r1) * (c2 - c1) == (c - c1) * (r2 - r1). So test every cell against every pair:

def part2(text: str) -> int:
    lines = text.split()
    antennas = {}
    for r, line in enumerate(lines):
        for c, ch in enumerate(line):
            if ch != ".":
                antennas.setdefault(ch, []).append((r, c))
    count = 0
    for r in range(len(lines)):
        for c in range(len(lines[0])):
            found = False
            for positions in antennas.values():
                for i in range(len(positions)):
                    for j in range(i + 1, len(positions)):
                        r1, c1 = positions[i]
                        r2, c2 = positions[j]
                        if (r - r1) * (c2 - c1) == (c - c1) * (r2 - r1):
                            found = True
            if found:
                count += 1
    return count

It’s slow in principle (cells × pairs), about 120 ms on the generated 50x50 map. But it can’t miss a cell, which makes it the reference the next step is tested against.

Step 2: walk the lines

Instead of asking every cell, go and find them. The cells on the line through a and b are a + k * step for every whole k, so start at a and step each way until the walk leaves the map:

from itertools import combinations
from math import gcd


def part2(text: str) -> int:
    antennas, cells = parse(text)
    antinodes = set()
    for group in antennas.values():
        for a, b in combinations(group, 2):
            d = b - a
            step = d / gcd(int(d.real), int(d.imag))
            for direction in (step, -step):
                p = a
                while p in cells:
                    antinodes.add(p)
                    p += direction
    return len(antinodes)

The walk starts on a and passes through b, so both antennas are counted without a special case. About 0.6 ms on the same generated map.

The step is b - a divided by the gcd of its two parts. Antennas two columns and four rows apart have a cell exactly between them, one column and two rows from each; step by the full (2, 4) and the walk jumps over it. gcd(0, n) is n (and gcd is never negative), so pairs in the same row or column reduce to a step of one cell in the right direction. A Python complex number always holds two floats, so the positions are floats all along; that’s fine, because small whole numbers are exact as floats and dividing each part by one of its own divisors leaves a whole number.

Most write-ups step by the full difference and get the right answer. That’s because, as people reported, no pair in the real inputs has a common factor. The example has none either, so I couldn’t check this here. Dividing is right in every case and costs nothing. The tests include a small map where it matters (3 antinodes with the gcd, 2 without), and check this step against step 1 on 300 random maps, which do contain such pairs.

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