main About me Back to Posts Personal Projects Links Privacy Contact
Today is day 3 of Advent of Code. See my recent post for an explanation.
The challenge today had us reading a ‘map’ with lines showing either “.” for an empty space, or “#” for a tree. We had to figure out how to walk the map and count the number of trees we’d hit, based on different slopes. It was challening, since I stick at arrays and such, but after many tries, I got both parts right!
Part 1’s Code:
# Advent of Code #3 part 2 - Starting at the top-left corner of your map and
# following a slope of right 3 and down 1, how many trees would you encounter?
treecount = 0
clearspace = '.'
tree = '#'
lineCtr = 0
colCnt = 3
with open("c:\\git\\advent-2020\\3.txt", "r") as f:
map = f.read().splitlines()
for line in map:
# example line: .........#....#.###.........##.
lineCtr += 1
if lineCtr == 1:
continue
if colCnt >= 31:
print("wrapping...")
colCnt = colCnt - 31
thisChar = line[colCnt]
if thisChar == tree:
treecount += 1
colCnt += 3
#if lineCtr >= 12:
# break
print("There are " + str(len(map)) + " lines on the map, of which, " + str(treecount) + " have trees in the path.")
Part 2’s Code:
# Advent of Code #3 part 2 - What do you get if you multiply together the number of trees
# encountered on each of the listed slopes?
report = ''
with open("c:\\git\\advent-2020\\3.txt", "r") as f:
map = f.read().splitlines()
def addToReport(value):
global report
report += value + "\n"
def getTrees(down, right):
lineCtr = 1
colCnt = right
treecount = 0
for line in map:
# example line: .........#....#.###.........##.
addToReport(str(lineCtr) + " " + line)
if (lineCtr == 1) or (down == 2 and lineCtr == 2):
lineCtr += 1
continue
if (down == 2) and (lineCtr % 2 == 0):
lineCtr += 1
continue
if colCnt >= 31:
colCnt = colCnt - 31
thisChar = line[colCnt]
if thisChar == '#':
treecount += 1
addToReport("thisChar =" + thisChar + " treecount = " + str(treecount) + " colCnt = " + str(colCnt))
colCnt += right
lineCtr += 1
print ("trees in loop (" + str(right) + "," + str(down) + ")= " + str(treecount))
return treecount
treesInAllLoops = getTrees(1,1) * getTrees(1,3) * getTrees(1,5) * getTrees(1,7) * getTrees(2,1)
fl = open("3-report.txt", "w")
fl.write(report)
fl.close()
print("There are " + str(treesInAllLoops) + " trees in all paths.")
Cheers!