-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay3.py
74 lines (54 loc) · 2.05 KB
/
Day3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
path = "./Inputs/day3.txt"
# path = "./Inputs/day3Test.txt"
def part1():
trees = 0
index = 3
fullTreeGrid = []
# read input file into a list
with open(path) as file:
initialTreeGrid = [list(line.strip()) for line in file]
# since the "same pattern repeats to the right many times", extend each row to handle this
for row in initialTreeGrid:
# get the approximate repeat-length of the pattern
repeatToRight = int(len(initialTreeGrid) / int(len(row)/index))
if(repeatToRight > 0):
row = row * repeatToRight
fullTreeGrid.append(row)
# count the trees
for row in fullTreeGrid[1:]: # the [1:] skips the first row
if(row[index] == '#'):
trees += 1
index += 3
print("Part 1:")
print(trees)
def part2():
# read input file into a list
with open(path) as file:
initialTreeGrid = [list(line.strip()) for line in file]
answer = countTrees(initialTreeGrid, 3, 1) * countTrees(initialTreeGrid, 1, 1) * countTrees(
initialTreeGrid, 5, 1) * countTrees(initialTreeGrid, 7, 1) * countTrees(initialTreeGrid, 1, 2)
print("Part 2:")
print(answer)
def countTrees(initialTreeGrid, right, down):
trees = 0
initialMoveRight = right
initialMoveDown = down
fullTreeGrid = []
# since the "same pattern repeats to the right many times", extend each row to handle this
for row in initialTreeGrid:
# get the approximate repeat-length of the pattern
# add 1 to account for rounding
repeatToRight = int(len(initialTreeGrid) / int(len(row)/initialMoveRight)) + 1
if(repeatToRight > 0):
row = row * repeatToRight
fullTreeGrid.append(row)
# count the trees
for index, row in enumerate(fullTreeGrid):
if(index == down):
if(row[right] == '#'):
trees += 1
right += initialMoveRight
down += initialMoveDown
return trees
part1()
part2()