Advent of Code 2020 – Day 3
Day 3 was the first that really presented some problems, and I admit, I did a “cheaty trick” to solve it. Part 1 and 2 use the same code as well, because Part 2 was a simple variation of Part 1.
For Day 3, you get a “map” of a forest with Trees. You have to count how many trees will need to be avoided for a particular path through the forest. The path is a straight line along a particular slope, (over right, down some). here is the sample forest:
..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#
So, the problem I ran into, is that the hash (#) in Python, creates comments. I am sure there is a way, but I could not figure out how to escape out the hash to compare and count it in an ‘if’ statement. So what I did instead of was replace all the #s in my map code, with ‘T’s. I can look for ‘T’s all day.
With that, here is a my solution:
def split_str(s): return [ch for ch in s] with open('day3datab.txt') as f: lines = [line.rstrip() for line in f] trees = 0 slopex = 1 slopey = 2 posx=0 posy=0 line_loop=len(lines) distance=len(lines)-2 #print distance while (posy<distance): #print trees posx=posx+slopex posy=posy+slopey #print str(posy)+"/"+str(distance) if(posx>=line_loop): posx=posx-line_loop #print str(posx)+","+str(posy) print str(lines[posy][posx]) whatis=str(lines[posy][posx]) if (whatis == "T"): trees+=1 print trees
The way the problem works is, the forest repeats to the right infinitely. So step one was getting the width of the forest repeat sequence, so I could loop my position back around as needed. Otherwise it’s a simple matter of updating the position of ‘row’ and ‘col’, checking if it needs to loop (is row position greater than the loop, if so subtract the loop value), then check for a T(ree).
Part 2 was the same problem, except you check several slopes and multiply the results together. To solve this I just adjusted my slope variables and then used a calculator to multiply the results.
I could have changed the code to ask for the slope each run, or even have it loop through several slopes until you tell it to end, when it would multiply the results itself, but frankly, I don’t have that kind of time. This is a fun side project to do while watching TV at night.