← blog

Twenty-Five Days · day 1 · both parts

Day 1: Historian Hysteria

the puzzle ↗ #aoc-2024#python

A gentle start: both parts are a few lines of Python. The interesting bit is in part 2, where the first thing you’d write is correct, fast enough on the puzzle’s size, and still quadratic.

The puzzle, in my words

The input is two columns of numbers, a left list and a right list. Pair the smallest number on the left with the smallest on the right, the second smallest with the second smallest, and so on, and add up how far apart the numbers in each pair are.

The example has six lines: the left list is 3, 4, 2, 1, 3, 3 and the right list is 4, 3, 5, 3, 9, 3. Sorted, the pairs are (1, 3), (2, 3), (3, 3), (3, 4), (3, 5) and (4, 9), with gaps 2, 1, 0, 1, 2 and 5: 11 in total.

Part 1: pair them up, smallest first

Part 1 on the example. Each round pairs the smallest unused number of each list and measures the gap on the number line.

Step 1: the first version

Read the lines into two lists, sort both, and walk them with one index:

def part1(text: str) -> int:
    left = []
    right = []
    for line in text.splitlines():
        a, b = line.split()
        left.append(int(a))
        right.append(int(b))
    left.sort()
    right.sort()
    total = 0
    for i in range(len(left)):
        total += abs(left[i] - right[i])
    return total

Step 2: slices and zip

text.split() with no argument splits on any run of whitespace, newlines included, so it gives every number in reading order: left, right, left, right. The two columns are then every second item, which is what the slices [0::2] and [1::2] take. zip pairs the two sorted lists, so the index goes, and sum takes the generator directly:

def columns(text: str) -> tuple[list[int], list[int]]:
    nums = [int(n) for n in text.split()]
    return nums[0::2], nums[1::2]


def part1(text: str) -> int:
    left, right = columns(text)
    return sum(abs(a - b) for a, b in zip(sorted(left), sorted(right)))

Sorting is all the work here. On a generated input of 1,000 lines of five-digit numbers, both versions take about 0.3 ms.

Part 2: how often each number appears

Now the order doesn’t matter. Each number in the left list counts for itself times the number of times it appears in the right list, and the answer, a “similarity score”, is the sum. In the example, 3 appears three times on the right, 4 once, and 2 and 1 not at all, so the score is 9 + 4 + 0 + 0 + 9 + 9 = 31.

Part 2 on the example. Count the right list once, then each left number is one lookup.

Step 1: list.count

The rule translates directly:

def part2(text: str) -> int:
    left, right = columns(text)
    score = 0
    for x in left:
        score += x * right.count(x)
    return score

It’s correct, and it’s what I’d write first. But right.count(x) has to look at every element of right to count them all, and it does that once per left number: n × n comparisons for n lines. On a generated input of 1,000 lines that’s about 6.5 ms, which is fine. On 10,000 lines it’s about 650 ms: ten times the input, a hundred times the time.

Step 2: count once with a Counter

Count the right list once instead. collections.Counter(right) is a dict from each number to how many times it appears, built in one pass, and looking up a number it has never seen gives 0 rather than a KeyError (without adding the key), so the 2 and the 1 in the example need no special case:

from collections import Counter


def part2(text: str) -> int:
    left, right = columns(text)
    counts = Counter(right)
    return sum(x * counts[x] for x in left)

That’s one pass over each list. On the same generated inputs it takes about 0.2 ms for 1,000 lines and 2 ms for 10,000, most of which is reading the numbers. The tests run both versions of each part on a few hundred random inputs, some with lots of repeated numbers, and check that they agree.

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