-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8.py
69 lines (51 loc) · 1.91 KB
/
day8.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
#!/usr/bin/env python3
from typing import Tuple
s = '''30373
25512
65332
33549
35390'''.split('\n')
with open('day8.input', 'r') as f:
s = f.read().strip().split('\n')
s = tuple(tuple(map(int, r)) for r in s)
s_ = tuple(zip(*s)) # s inverted: columns are now rows
def outer_visible(ts: Tuple[int]) -> Tuple[bool]:
v = tuple( t > max((*ts[:i], -1)) for i, t in enumerate(ts) )
return v
rows, cols = [], []
for r, c in zip(s, s_):
ltr, utd = map(outer_visible, (r, c))
rtl, dtu = map(lambda t: outer_visible(t[::-1])[::-1], (r, c))
row = [ l or r for l, r in zip(ltr, rtl) ]
col = [ u or d for u, d in zip(utd, dtu) ]
rows.append(row)
cols.append(col)
total = 0
for r, c in zip(rows, zip(*cols)):
total += sum(r[i] or c[i] for i in range(len(rows)))
print(total)
def inner_visible(i: int, ts: Tuple[int]) -> int:
count, t, i = 0, ts[i], i - 1
while ts[i] < t and i >= 0:
count += 1
i -= 1
count += int(i >= 0) # blocked by this tree
return count
scores = []
for i, r in enumerate(s):
for j, t in enumerate(r):
c = s_[j]
ltr, utd = inner_visible(j, r), inner_visible(i, c)
rtl = inner_visible(len(r) - j - 1, r[::-1])
dtu = inner_visible(len(c) - i - 1, c[::-1])
sc = ltr * rtl * utd * dtu
scores.append(sc)
print(max(scores))
# `outer_visible()` returns True for each tree in the row that is visible from
# the left (i.e bigger than the maximum of trees to its left).
# there are four directions to consider, left-to-right ways (`ltr`, `rtl`) and
# up-to-down (`utd`, `dtu`). `zip(*s)` inverts a list of lists so that moving
# "down a column" becomes "along a row". this way, we can use `outer_visible()`
# for all directions and combine the results using `or`.
# `inner_visible()` returns how many trees can be seen leftways from the given
# similarly the grid is rotated and results combined, this time using *.