From 968ade2c193d80db7a6170ee1eb44e120aa00992 Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Mon, 12 Dec 2022 11:03:58 +0100 Subject: Day 12 --- day12/__init__.py | 47 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 13 deletions(-) (limited to 'day12') diff --git a/day12/__init__.py b/day12/__init__.py index 52fa2e7..55545f7 100644 --- a/day12/__init__.py +++ b/day12/__init__.py @@ -14,28 +14,31 @@ class Map: self.height = len(map) self.width = len(map[0]) - self.start = self.find_unique_position("S") - self.end = self.find_unique_position("E") + try: + self.start = next(self.find_position("S")) + except StopIteration: + self.start = (0, 0) - def find_unique_position(self, value: str) -> Tuple[int, int]: + try: + self.end = next(self.find_position("E")) + except StopIteration: + self.start = (0, 0) + + def find_position(self, value: str) -> Iterator[Tuple[int, int]]: for y in range(self.height): for x in range(self.width): if self.map[y][x] == value: - return x, y + yield x, y def neighbours(self, x: int, y: int) -> Iterator[Tuple[int, int]]: for dy in range(max(0, y - 1), min(self.height, y + 2)): for dx in range(max(0, x - 1), min(self.width, x + 2)): - current_elevation = self.elevation(x, y) - neigbour_elevation = self.elevation(dx, dy) - if ( (dy == y and dx == x) or (dy == y - 1 and dx == x - 1) or (dy == y - 1 and dx == x + 1) or (dy == y + 1 and dx == x - 1) or (dy == y + 1 and dx == x + 1) - or (abs(neigbour_elevation - current_elevation) > 1) ): continue yield dx, dy @@ -56,12 +59,12 @@ class Map: class Assignment(BaseAssignment, ABC): def distance(self, map: Map, a: Tuple[int, int], b: Tuple[int, int]): - distance = abs(map.elevation(*a) - map.elevation(*b)) + distance = map.elevation(*b) - map.elevation(*a) if distance > 1: return inf - return distance + return 1 def heuristic(self, map: Map, a: Tuple[int, int]): dx = abs(map.start[0] - a[0]) @@ -120,8 +123,6 @@ class AssignmentOne(Assignment): def run(self, input: Iterator) -> Any: map = Map(map=list(input)) - print(map.start, map.end) - path = self.a_star( map, map.start, @@ -134,4 +135,24 @@ class AssignmentOne(Assignment): class AssignmentTwo(Assignment): - pass + example_result = 29 + + def run(self, input: Iterator) -> Any: + map = Map(list(input)) + lengths = [] + + for a in map.find_position("a"): + try: + path = self.a_star( + map, + a, + map.end, + distance=lambda a, b: self.distance(map, a, b), + heuristic=lambda a: self.heuristic(map, a), + ) + + lengths.append(len(path) - 1) + except RuntimeError: + continue + + return sorted(lengths)[0] -- cgit v1.2.3