aoc/2022/day08.py

96 lines
2.3 KiB
Python
Raw Normal View History

2022-12-17 11:32:52 -05:00
#!/usr/bin/env python3
from typing import TextIO
# left
# right
# up
# down
trees = []
def part1(heights: TextIO) -> int:
visible = 0
for row in heights:
trees.append([int(num) for num in row.strip()])
for row in range(len(trees)):
for tree in range(len(trees[row])):
if tree in (
0,
len(trees[row]) - 1,
) or row in (0, len(trees) - 1):
visible += 1
elif (
all(x < trees[row][tree] for x in trees[row][:tree])
or all(x < trees[row][tree] for x in trees[row][tree + 1 :])
or all(trees[row][tree] > trees[x][tree] for x in range(row))
or all(
trees[row][tree] > trees[x][tree]
for x in range(row + 1, len(trees))
)
):
visible += 1
return visible
def part2() -> int:
scores = []
for row in range(len(trees)):
for c in range(len(trees[row])):
left = 0
right = 0
up = 0
down = 0 # ??
if c in (
0,
len(trees[row]) - 1,
) or row in (0, len(trees) - 1):
continue # score will be 0 anyways, disregard
# left score
for x in reversed(trees[row][:c]):
if trees[row][c] > x:
left += 1
else:
left += 1
break
# right score
for x in trees[row][c + 1 :]:
if trees[row][c] > x:
right += 1
else:
right += 1
break
# up
for x in reversed(range(row)):
if trees[row][c] > trees[x][c]:
up += 1
else:
up += 1
break
# down
for x in range(row + 1, len(trees)):
if trees[row][c] > trees[x][c]:
down += 1
else:
down += 1
break
scores.append(left * right * up * down)
return max(scores)
if __name__ == "__main__":
print(part1(open("day08.txt")))
print(part2())