Skip to content
advent of code 2016

day 08

two-factor authentication

approach

the screen is a 50×6 grid of . characters. each line is parsed into a tuple, rect, rotate_row or rotate_column with two numbers, and a match statement applies it to the grid in place: rect fills the top-left block with #, and the rotations shift one row or column with wrap-around.

part 1 counts the # cells after all instructions. part 2 prints the grid, and the answer is read off the letters it shows.

the trick

the rotation is done in place by following cycles: each value is carried k positions ahead and swapped with whatever was there, until the walk returns to where it started.

python
def rotate_row(grid, row, k):
    arr = grid[row]
    rem = n = len(arr)
    i = 0
    while rem and i < n:
        start = i
        prev = arr[i]
        while True:
            ni = (i + k) % n
            prev, arr[ni] = arr[ni], prev
            i = ni
            rem -= 1
            if ni == start:
                break
        i += 1