Advent of Code: Day #03 - Toboggan Trajectory
2-3 minutes
Introduction
With our toboggan successfully rented we can set off to the airport but first we need to know how many trees are in the way on the slope down.
Task One
Given an infinitely repeating map of trees in the x dimension find how many trees the toboggan will hit on a slope of right 3, down 1 departing from top left to to the bottom of the input.
Reading in the data
Today I didn't do any pre-processing when reading in the data and simply added each line of the input data to an array.
def read_data(path):forest = []with open(path, "r") as file:for line in file.readlines():forest.append(line)return forest
The Solution
This problem can be solved by checking if the item at x, y position of the toboggan is a tree or not. Since the pattern is infinitely repeated in the x direction we can just use a modulo to wrap back round to other side of the input.
def task_one(dataset):tree_count = 0tree_height = len(dataset) - 1tree_width = len(dataset[0]) - 1pos = [3, 1]for _ in range(tree_height):if dataset[pos[1]][pos[0]] == "#":tree_count += 1pos[0] += 3pos[1] += 1pos[0] %= tree_widthreturn tree_count
Task Two
The Solution
Task two was the same as task apart from we had to count the trees for several different slopes and return the product.
def task_two(dataset):paths = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]total = 1for path in paths:tree_count = 0tree_height = len(dataset) - 1tree_width = len(dataset[0]) - 1pos = deepcopy(path)for _ in range(tree_height // pos[1]):if dataset[pos[1]][pos[0]] == "#":tree_count += 1pos[0] += path[0]pos[1] += path[1]pos[0] %= tree_widthtotal *= tree_countreturn total
Links
Leaderboard Code: 353270-1fc6ef28
Github Repository A link to the github repo containing all the days.
main.py A direct download of the main.py script
1.3Kb