#### Advent of Code 2020 - Day 3

in   code   ,

Day 3 of AoC 2020 (Toboggan Trajectory) is easy enough to solve in any language, but we’re sticking with Python for this. As always, spoilers ahead.

The problem gives us a map description, with '#' describing the location of trees on integer coordinates, and '.' describing open space. It also states that the map repeats indefinitely to the right. That is $\forall x \in \mathbb{Z}, x_0 = x \mod length$, where $length$ is the length of the rows in the input.

Also, we need to find the number of trees when traversing a given slope. Since all the slopes given have mutually prime $\Delta x, \Delta y$, both are integers, and at least one of them is $1$, we can calculate the integer nodes that we’ll end up on by using the following formula - $x_{i+1} = (x_i + \Delta x) \mod length; x_0 = 0$ and $y_{i+1} = (y_i + \Delta y); y_0 = 0 ; y_i < height$

This can be simply implemented using the code below:

with open("input") as datafile:
data = []
for line in datafile:
data.append([x == '#' for x in line.strip()])

def trees(dx, dy):
# Calculate the number of trees for the given slope
x, y = 0, 0
trees = 0
while y < len(data):
trees += int(data[y][x])
x = (x + dx) % len(data)
y += 1

return trees

# Part 1, return the trees for 1 slope
print(trees(3, 1))

# Part 2, return the product of trees for all slopes
from functools import reduce
print(reduce(lambda x,y: x*y, (trees(dx, dy) for dx, dy in
[(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)])))

Recent Posts