Hello! Continuing our advent of code journey for 2020, we are at day 03.
Spoilers Ahead! The full solution to the problem is available here.
Problem: Given a grid of #‘s and .‘s - find the number of #‘s while traversing through the grid across a slope.
The # are referred to as trees, and . are referred to as squares.
The problem has an additional scenario wherein the columns in the grid can extend multiple times, as much as necessary. So essentially we have an M X N Grid, where N -> Infinity.
Let’s look at a sample input:
For the above input, while counting from (0,0) through every slope moving 3 columns to the right and 1 row downwards on every step, we can see that the number of #‘s (trees) across the slope is 7.
Let’s look at how we can solve this problem. The algorithm would look something like:
Parse the input and convert it into a Vec<Vec<char>> ie. a Grid
Traverse from start of the Grid along the specified slope, by moving across rows and columns
After reaching the element at the end of a given slope, if the element is a #, increment counter.
Continue moving along till you reach the last row in the Grid.
While traversing the Grid, if you reach the end of the last column wrap around to the first column using col[index % col.len()].
This is necessary as the problem mentions that the Grid is not fixed on the right, and can extend as much as necessary.
The grid of characters can be built from the given input:
The other input we need to process is the slope, which is of the format direction steps, direction steps . . . where each instruction to traverse across the slope is separated by a comma.
Let’s parse this, and return the number of rows and columns we need to jump. We’ll define a struct Jump that will hold these values.
The logic to parse the slope, would be as follows:
For the slope right 3, down 1 the parse_slope function returns Jump { column: 3, row: 1}.
All that’s left to do is implement the core logic to traverse the grid, and find the number of #s. We can write the function so that it can also find the count of any character in a grid, across the slope.
The process function is essentially a Driver function, that gets the count for the given input string of # a . along a given slope direction.
For Part 2, the same code essentially can be reused but we just need to find the product of all the number of trees across different slope directions.