Advent of Code 2022 - 8

Day 8: Treetop Tree House

https://adventofcode.com/2022/day/8

1
2
3
4
5
6
7
import numpy as np

with open('08.txt', 'r') as fp:
lines = fp.readlines()
grid = [[int(c) for c in line.strip()] for line in lines]
grid = np.array(grid)
n_r, n_c = grid.shape

Part One

1
2
3
4
5
6
7
8
9
10
11
visible = 0
for i in range(n_r):
for j in range(n_c):
h = grid[i][j]
w = grid[i,0:j]
e = grid[i,j+1:]
n = grid[0:i,j]
s = grid[i+1:,j]
if any([all(h > _ for _ in dir) for dir in [w, e, n, s]]):
visible += 1
print(visible)

Answer: 1845

Part Two

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def view_dist(h, view):
dist = 0
for v in view:
dist += 1
if v >= h:
break
return dist


score = 0
for i in range(n_r):
for j in range(n_c):
h = grid[i][j]
w = grid[i,0:j][::-1]
e = grid[i,j+1:]
n = grid[0:i,j][::-1]
s = grid[i+1:,j]
score = max(score,
(view_dist(h, w)
* view_dist(h, e)
* view_dist(h, n)
* view_dist(h, s)))
print(score)

Answer: 230112