This repository has been archived by the owner on Oct 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_08.py
98 lines (87 loc) · 2.72 KB
/
day_08.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from pathlib import Path
from typing import List
import numpy as np
from constants import INPUTS_DIR, UTF_8
INPUT_PATH = Path(INPUTS_DIR) / "day-08.txt"
# INPUT_PATH = Path(INPUTS_DIR) / "example.txt"
def main1(forest: List[List[int]]) -> int:
n_rows = len(forest)
n_cols = len(forest[0])
visible = np.zeros((n_rows, n_cols), dtype=bool)
visible[0, :] = True
visible[-1, :] = True
visible[:, 0] = True
visible[:, -1] = True
for row in range(n_rows):
# from left
tallest = forest[row][0]
for col in range(1, n_cols):
if forest[row][col] > tallest:
tallest = forest[row][col]
visible[row, col] = True
# from right
tallest = forest[row][-1]
for col in range(n_cols - 2, -1, -1):
if forest[row][col] > tallest:
tallest = forest[row][col]
visible[row, col] = True
for col in range(n_cols):
# from up
tallest = forest[0][col]
for row in range(1, n_rows):
if forest[row][col] > tallest:
tallest = forest[row][col]
visible[row, col] = True
# from down
tallest = forest[-1][col]
for row in range(n_rows - 2, -1, -1):
if forest[row][col] > tallest:
tallest = forest[row][col]
visible[row, col] = True
return visible.sum()
def score(forest: List[List[int]], row: int, col: int) -> int:
n_rows = len(forest)
n_cols = len(forest[0])
this_height = forest[row][col]
# up
for i in range(row - 1, -1, -1):
if forest[i][col] >= this_height:
up = row - i
break
else:
up = row
# down
for i in range(row + 1, n_rows):
if forest[i][col] >= this_height:
down = i - row
break
else:
down = n_rows - row - 1
# left
for i in range(col - 1, -1, -1):
if forest[row][i] >= this_height:
left = col - i
break
else:
left = col
# right
for i in range(col + 1, n_cols):
if forest[row][i] >= this_height:
right = i - col
break
else:
right = n_cols - col - 1
return up * down * left * right
def main2(forest: List[List[int]]) -> int:
highest = 0
for i in range(1, len(forest) - 1):
for j in range(1, len(forest[0]) - 1):
highest = max(highest, score(forest, i, j))
return highest
if __name__ == "__main__":
with open(INPUT_PATH, "r", encoding=UTF_8) as f:
forest_ = [list(map(int, line_.strip())) for line_ in f.readlines()]
ans = main1(forest_)
print("part 1:", ans)
ans = main2(forest_)
print("part 2:", ans)