Last active
December 8, 2022 19:39
-
-
Save jsbueno/f92e95c4c8edd8aac55a631d0c848cbb to your computer and use it in GitHub Desktop.
Advent of code 2022, day8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Puzzles at: https://adventofcode.com/2022/day/8 | |
SPOILER ALERT!!! | |
Not super-smart - but very conffy to look and operate at the map. | |
Probably with some heavy caching (using attached dicts) could go from quadractic time to near linear time. | |
(Or O(MxN) M being the total points, N being max (Width, Height)) | |
""" | |
class Trees: | |
def __init__(self, data): | |
self.data = data.splitlines() | |
self.width = len(self.data[0]) | |
self.height = len(self.data) | |
def __getitem__(self, pos): | |
if not 0 <= pos[0] < self.width or not 0 <= pos[1] < self.height: | |
return -1 | |
return int(self.data[pos[1]][pos[0]]) | |
def minother(self, pos): | |
return min(self._maxother(pos, direction)[0] for direction in [(1,0), (0, 1), (-1, 0), (0, -1)]) | |
def _maxother(self, pos, direction, threshold=0): | |
answer = -1 | |
returned = -2 | |
count = 0 | |
lineofview = True | |
while returned != -1: | |
pos = (pos[0] + direction[0], pos[1] + direction[1]) | |
if (returned:=self[pos]) > answer: | |
answer = returned | |
if lineofview and returned < threshold: | |
count += 1 | |
elif returned >= threshold: | |
if lineofview: | |
count += 1 | |
lineofview = 0 | |
if lineofview: | |
count -= 1 | |
return answer, count | |
def linesofview(self, pos): | |
return [self._maxother(pos, direction, self[pos])[1] for direction in [(1,0), (0, 1), (-1, 0), (0, -1)]] | |
def visible(self, pos): | |
return self.minother(pos) < self[pos] | |
def __iter__(self): | |
for x in range(self.width): | |
for y in range(self.height): | |
yield ((x,y), self[(x,y)]) | |
def answer(self): | |
return sum(self.visible(pos) for pos, value in self) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment