← blog

Twenty-Five Days · day 5 · both parts

Day 5: Print Queue

the puzzle ↗ #aoc-2024#python

Part 1 is a check against a set of pairs. Part 2 asks for a repair, and the interesting part is which ways of repairing are actually allowed by the rules you’re given.

The puzzle, in my words

The input is a list of rules like 47|53, meaning page 47 has to be printed before page 53 if an update contains both, and then a list of updates, each a list of pages. A rule only counts for an update that has both of its pages. Find the updates that already follow every rule that applies to them, and add up their middle pages.

The example has 21 rules over seven pages and six updates. The first three pass, the other three each break at least one rule (75,97,... puts 75 first, but 97|75 says otherwise), and the middle pages of the three that pass add up to 61 + 53 + 29 = 143.

Part 1: which updates are already in order

Part 1 on the example. Left: the rules, row page before column page. Right: the updates, checked pair by pair.

Step 1: the first version

Read the rules as pairs and the updates as lists. An update is in order if no pair of its pages, taken left to right, has a rule saying the right one should come first.

def parse(text: str) -> tuple[list[tuple[int, int]], list[list[int]]]:
    top, bottom = text.strip().split("\n\n")
    rules = [tuple(map(int, line.split("|"))) for line in top.split()]
    updates = [list(map(int, line.split(","))) for line in bottom.split()]
    return rules, updates


def part1(text: str) -> int:
    rules, updates = parse(text)
    total = 0
    for update in updates:
        ok = True
        for i in range(len(update)):
            for j in range(i + 1, len(update)):
                if (update[j], update[i]) in rules:
                    ok = False
        if ok:
            total += update[len(update) // 2]
    return total

Checking for the broken rule, rather than for the rule that agrees, matters: a pair with no rule at all is fine. The example happens to have a rule for every pair of its seven pages, so here it would make no difference.

Step 2: a set of pairs

in on a list walks the list. On a generated input of 1,176 rules and 200 updates of up to 23 pages, that’s a scan of up to all the rules for every pair of pages, and the step 1 version takes about 0.7 s. Put the rules in a set and each lookup is a hash. itertools.combinations(update, 2) yields the pairs in the update’s own order, left page first, and all() stops at the first broken rule:

from itertools import combinations


def in_order(update: list[int], rules: set[tuple[int, int]]) -> bool:
    return all((b, a) not in rules for a, b in combinations(update, 2))


def part1(text: str) -> int:
    rules, updates = parse(text)
    rules = set(rules)
    return sum(u[len(u) // 2] for u in updates if in_order(u, rules))

About 1 ms on the same generated input.

Part 2: putting the others in order

Now take the updates that failed, rearrange each so it follows its rules, and add up their middle pages. In the example the three become 97,75,47,61,53, 61,29,13 and 97,75,47,29,13: 47 + 29 + 47 = 123.

Part 2 on the three wrong updates: count the pages that must come before each page. The counts are the positions.

Step 1: swap until nothing is broken

The direct repair: find a pair that breaks a rule, swap the two pages, and look again from the start.

def part2(text: str) -> int:
    rules, updates = parse(text)
    rules = set(rules)
    total = 0
    for update in updates:
        if in_order(update, rules):
            continue
        pages = update[:]
        fixed = False
        while not fixed:
            fixed = True
            for i, j in combinations(range(len(pages)), 2):
                if (pages[j], pages[i]) in rules:
                    pages[i], pages[j] = pages[j], pages[i]
                    fixed = False
                    break
        total += pages[len(pages) // 2]
    return total

It’s worth asking why this stops. If the rules for an update have no cycle, there is some order that follows all of them. Every swap here exchanges two pages that are the wrong way round compared with that order, and swapping such a pair always lowers the number of pairs that are the wrong way round. So it ends, and it only ends once no rule is broken. That doesn’t need a rule for every pair, and the tests run it on random rule sets with gaps. It is slow, though: restarting the scan after every swap costs about 110 ms on the generated input.

Step 2: let sorted do it

A rule is a comparison: a|b means a sorts first. sorted takes a key function rather than a comparison, and functools.cmp_to_key turns a comparison function (negative for “a first”, positive for “b first”) into one:

from functools import cmp_to_key


def part2(text: str) -> int:
    rules, updates = parse(text)
    rules = set(rules)

    def compare(a: int, b: int) -> int:
        return -1 if (a, b) in rules else 1 if (b, a) in rules else 0

    total = 0
    for update in updates:
        if not in_order(update, rules):
            pages = sorted(update, key=cmp_to_key(compare))
            total += pages[len(pages) // 2]
    return total

This one does need something from the input. A sort assumes its comparison describes one consistent order: if a is before b and b before c, then a is before c. With gaps in the rules, compare returns 0 for two pages that may still have to go in a particular order because of a third page between them, and the sort can’t see that. It’s safe when, within each update, every pair of pages has a rule and those rules have no cycle. The example has exactly that: its 21 rules are every pair of its 7 pages, and a test checks it. For real inputs, comparator sorts like this one are a common solution and are widely reported to give the right answer, which suggests the property holds there too. Write-ups also report that the full rule set, across all updates, has a cycle, so there’s no single global order to sort by. Neither could be checked here.

About 5 ms on the generated input, which was built to have the property.

Step 3: only the middle is needed

If an update’s rules put its n pages in one total order, a page’s position is the number of other pages that have to come before it. The first page has 0, the last has n - 1, and the middle page is the one with exactly n // 2. So there’s no need to sort at all; count, and stop at the first page with the right count:

def middle(update: list[int], rules: set[tuple[int, int]]) -> int:
    half = len(update) // 2
    return next(p for p in update if sum((q, p) in rules for q in update) == half)


def part2(text: str) -> int:
    rules, updates = parse(text)
    rules = set(rules)
    return sum(middle(u, rules) for u in updates if not in_order(u, rules))

That’s what the animation shows: the count under each page is where it belongs. It relies on the same property as step 2, and on updates of up to 23 pages it isn’t dramatically faster: on the generated input, about 2.5 ms of counting against 3.5 ms of sorting, plus about 1 ms for the part 1 check that picks out the wrong updates in both. What I like about it is that it says what the answer actually depends on: the middle page is fixed by the counts, and the rest of the order never has to be built.

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