Skip to content
advent of code 2020

day 03

toboggan trajectory

approach

the map is kept as a list of strings, and count_trees walks down it with a given row and column step, counting the # cells it lands on. the map repeats to the right, so the column is taken modulo the row width instead of building a wider grid.

part 1 uses one slope (down 1, right 3). part 2 runs five slopes and multiplies the tree counts together.

the trick

a pattern that repeats sideways forever is just col % width.

python
def count_trees(matrix, drow, dcol):
    n, m = len(matrix), len(matrix[0])
    col = res = 0
    for row in range(0, n, drow):
        res += int(matrix[row][col] == '#')
        col = (col + dcol) % m
    return res