Skip to content
advent of code 2023

day 13

point of incidence

approach

each pattern becomes a grid of 0s and 1s. for a candidate line, h_reflect and v_reflect pair up rows (or columns) outward from it and count how many cells differ, giving up as soon as more than one does.

part 1 picks the line with zero differences. part 2 picks the line with exactly one difference, which is the line the smudge creates; an assert checks there is only one per pattern. vertical lines count as their column number and horizontal ones as 100 times their row.

the trick

count mismatched cells across the mirror: 0 is the original line, exactly 1 is the smudged one.

python
def h_reflect(pattern, r):
    res = 0
    for r1, r2 in zip(reversed(pattern[:r]), pattern[r:]):
        res += diff(r1, r2)
        if res > 1:
            return None
    return res

def col(pattern, c):
    return [row[c] for row in pattern]

def diff(i1, i2):
    return sum(i != j for i, j in zip(i1, i2))