This series looks at the Advent of Code challenges.
As one of my goals, I’m working through challenges. This post looks at day 3.
Part 1
Day 3 was tough. The explanation isn’t great, at least, I didn’t get it at first. Essentially you have a map, and then you have some slope. The first part has a slope of right 3, down 1. If you move, assuming the upper left is (1,1), the next spot is 2, 4. That’s if you count going down as positive.
Here’s the map:
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
If I count each space, then there is a period (.) in this (2,4) space. If it’s a tree, then there is a hash (#) there. We are trying to count trees before we hit bottom.
The trick I missed is that the map we’ve given repeats. It repeats to the right as often as needed to get to the bottom.
This is really a coordinate problem, counting each down as we move, and repeating the map. The trick often in a short width here is to do the math to wrap around from the right to left if you run out of room.
In SQL, I used a loop. I didn’t spend a ton of time, but couldn’t see a good way to avoid this as I need this to be readable, and I need this to keep working through the map. Here’s the code:
WHILE @currentrow <= @rows
BEGIN
SELECT @currentcol += @right
IF @currentcol > @width
SELECT @currentcol = @currentcol - @width
SELECT @currentrow += @down;SELECT @trees = @trees + CASE
WHEN SUBSTRING(dataval, @currentcol, 1) = '#' THEN 1
ELSE 0
end
FROM day3
WHERE rowkey = @currentrow
END
SELECT @trees AS TreeCount
I move, count the value if there’s as tree, and then continue moving through the next rows. The WHERE clause orients the rows.
It worked. I go the right answer here.
Part 2
In part 2, this changes to checking a number of sloops and then multiplying the results together. In terms of my code, this is really a repetitive way of running the code again. I could have used different variables and checked multiple slopes at once, but I was busy.
In python, I did something similar. I essentially calculated the next X and Y position, and then looped through the file. Each time the Y matched the current row, I checked for the matching #. If it matched, increment.
Once I matched the correct Y, I incremented X and Y.