← blog

Twenty-Five Days · day 2 · both parts

Day 2: Red-Nosed Reports

the puzzle ↗ #aoc-2024#python

A short one. Part 1 is a check on neighbouring numbers, and pairwise with a set makes it two lines. Part 2 can be done by trying everything, and the interesting part is seeing why you only need to try two things.

The puzzle, in my words

Each line of the input is a report: a list of numbers, called levels. A report is safe if its levels only go up or only go down, and each step between neighbours is 1, 2 or 3. Count the safe reports.

The example has six reports of five levels. 7 6 4 2 1 and 1 3 6 7 9 are safe. 1 2 7 8 9 jumps by 5, 9 7 6 2 1 drops by 4, 1 3 2 4 5 goes up and then down, and 8 6 4 4 1 has a step of 0. So 2 are safe.

Part 1: steady climbs and falls

Part 1 on the example. The first step sets the direction; a red step makes the report unsafe.

Step 1: the first version

The first step decides the direction. Then check every step against it; for a decreasing report, flip the sign of each step so the same 1..3 check works both ways. Stop at the first bad step.

def part1(text: str) -> int:
    count = 0
    for line in text.splitlines():
        levels = [int(x) for x in line.split()]
        if not levels:
            continue
        increasing = levels[1] > levels[0]
        safe = True
        for i in range(len(levels) - 1):
            diff = levels[i + 1] - levels[i]
            if not increasing:
                diff = -diff
            if diff < 1 or diff > 3:
                safe = False
                break
        if safe:
            count += 1
    return count

A first step of 0 counts as decreasing here, but that doesn’t matter: a step of 0 fails the check in either direction.

Step 2: the set of steps

Look at the rule from the other side: a report is safe when every step is one of 1, 2, 3, or every step is one of -1, -2, -3. itertools.pairwise (Python 3.10+) yields the neighbouring pairs, the steps go into a set, and <= on sets is “is a subset of”:

from itertools import pairwise


def reports(text: str) -> list[list[int]]:
    return [[int(x) for x in line.split()] for line in text.splitlines() if line.strip()]


def is_safe(levels: list[int]) -> bool:
    steps = {b - a for a, b in pairwise(levels)}
    return steps <= {1, 2, 3} or steps <= {-1, -2, -3}


def part1(text: str) -> int:
    return sum(is_safe(levels) for levels in reports(text))

No direction variable, no sign flip, no flag. For 1 3 2 4 5 the steps are {2, -1, 1}, which is a subset of neither.

This version is clearer, not faster. It always works out every step, where step 1 stops at the first bad one: on a generated input of 1,000 reports of 5 to 8 levels (the size people describe for the real input), step 1 takes about 0.8 ms and step 2 about 1.3 ms.

Part 2: one level forgiven

Now a report also counts if deleting one of its levels leaves a safe report. In the example, 1 3 2 4 5 is safe without its 3 and 8 6 4 4 1 without one of its 4s. The other two can’t be fixed, so 4 are safe.

Part 2 on the example: for an unsafe report, drop each level in turn until one drop leaves a safe report.

Step 1: try every deletion

Do what the rule says, with the part 1 check. A report of n levels has n ways to drop one:

def part2(text: str) -> int:
    count = 0
    for levels in reports(text):
        if is_safe(levels) or any(
            is_safe(levels[:i] + levels[i + 1 :]) for i in range(len(levels))
        ):
            count += 1
    return count

any stops at the first deletion that works, as the animation does. Each try builds a new list, so a report of n levels costs O(n²). With 5 to 8 levels that’s nothing: about 3.6 ms on the same generated input.

Step 2: only two levels are worth deleting

Pick a direction and find the first step that breaks the rule, say between levels i and i + 1. Deleting some level k only changes the steps that touch k. If k is anything other than i or i + 1, that bad step is still there and the report is still unsafe. So in each direction there are only two deletions to try:

def first_bad(levels: list[int], sign: int) -> int | None:
    for i, (a, b) in enumerate(pairwise(levels)):
        if not 1 <= (b - a) * sign <= 3:
            return i
    return None


def is_safe_dampened(levels: list[int]) -> bool:
    for sign in (1, -1):  # up, then down
        i = first_bad(levels, sign)
        if i is None:
            return True
        for k in (i, i + 1):
            if first_bad(levels[:k] + levels[k + 1 :], sign) is None:
                return True
    return False


def part2(text: str) -> int:
    return sum(is_safe_dampened(levels) for levels in reports(text))

In the example, checked going down, 8 6 4 4 1 first breaks at the step from 4 to 4, between its 3rd and 4th levels. Deleting the first of those 4s works, which is the drop the animation finds on its third try.

That’s at most four scans per report, so O(n) rather than O(n²). On the real-sized generated input it hardly matters (2.4 ms against 3.6 ms). On a stretched generated input of 100 reports with 1,000 levels each, trying every deletion takes 3.8 s and this version 16 ms. Because it’s easier to get wrong, the tests run it against step 1 on 5,000 random reports and check they agree.

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