Skip to content

Commit eb8c0b8

Browse files
committed
Solve 2022 Day 8 in python
1 parent 115581f commit eb8c0b8

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

2022/Day8/python/solve.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
from collections import defaultdict
2+
from functools import reduce
3+
import os
4+
import re
5+
from operator import mul
6+
7+
8+
def column(matrix, i):
9+
return [row[i] for row in matrix]
10+
11+
12+
def part1(lines: list[str]):
13+
visible_trees = []
14+
grid = [
15+
list(line.replace("\n", "")) for line in lines
16+
]
17+
18+
for y, col in enumerate(grid):
19+
for x, tree in enumerate(col):
20+
up = column(grid, x)[:y]
21+
down = column(grid, x)[y + 1:]
22+
left = grid[y][:x]
23+
right = grid[y][x + 1:]
24+
25+
if len(up) <= 0 or len(down) <= 0 or len(left) <= 0 or len(right) <= 0:
26+
visible_trees.append(tree)
27+
continue
28+
29+
up.sort(reverse=True)
30+
down.sort(reverse=True)
31+
left.sort(reverse=True)
32+
right.sort(reverse=True)
33+
if up[0] < tree or down[0] < tree or left[0] < tree or right[0] < tree:
34+
visible_trees.append(tree)
35+
pass
36+
return len(visible_trees)
37+
38+
39+
def part2(lines):
40+
highest_score = 0
41+
grid = [
42+
list(line.replace("\n", "")) for line in lines
43+
]
44+
45+
for y, col in enumerate(grid):
46+
for x, tree in enumerate(col):
47+
up = column(grid, x)[:y]
48+
down = column(grid, x)[y + 1:]
49+
left = grid[y][:x]
50+
right = grid[y][x + 1:]
51+
52+
# Adjust viewing angle
53+
left.reverse()
54+
up.reverse()
55+
56+
trees_visible = {
57+
"up": 0,
58+
"down": 0,
59+
"left": 0,
60+
"right": 0,
61+
}
62+
63+
for i, other in enumerate(up):
64+
trees_visible["up"] += 1
65+
if other >= tree:
66+
break
67+
for i, other in enumerate(down):
68+
trees_visible["down"] += 1
69+
if other >= tree:
70+
break
71+
for i, other in enumerate(left):
72+
trees_visible["left"] += 1
73+
if other >= tree:
74+
break
75+
for i, other in enumerate(right):
76+
trees_visible["right"] += 1
77+
if other >= tree:
78+
break
79+
80+
score = trees_visible["up"] * trees_visible["down"] * \
81+
trees_visible["left"] * trees_visible["right"]
82+
83+
if score > highest_score:
84+
highest_score = score
85+
return highest_score
86+
87+
88+
dirname = os.path.dirname(__file__)
89+
filename = os.path.join(dirname, '../input.txt')
90+
with open(filename) as f:
91+
lines = f.readlines()
92+
93+
print(part1(lines))
94+
print(part2(lines))

0 commit comments

Comments
 (0)