From 2c92e9bbac02e6c80982b9c114bdab7c63be5297 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Sat, 7 Dec 2024 05:45:53 +0100 Subject: [PATCH] day6 - use internal seen --- day06.py | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/day06.py b/day06.py index e7059ef..0e30e45 100644 --- a/day06.py +++ b/day06.py @@ -6,25 +6,6 @@ from tools.grid import Grid DIRECTIONS = [(0, -1), (1, 0), (0, 1), (-1, 0)] -def walk_room(grid: Grid, start: Coordinate) -> tuple[set, bool]: - cur_pos = start - dir_index = 0 - visited = set() - while grid.isWithinBoundaries(cur_pos): - if (cur_pos, dir_index) in visited: - return set(x[0] for x in visited), True - - visited.add((cur_pos, dir_index)) - next_pos = cur_pos + DIRECTIONS[dir_index] - while grid.get(next_pos): - dir_index = (dir_index + 1) % len(DIRECTIONS) - next_pos = cur_pos + DIRECTIONS[dir_index] - - cur_pos = next_pos - - return visited, False - - class Day(AOCDay): inputs = [ [ @@ -44,13 +25,32 @@ class Day(AOCDay): return grid, start + def walk_room(self, grid: Grid, start: Coordinate) -> bool: + cur_pos = start + dir_index = 0 + self.seen_reset() + while grid.isWithinBoundaries(cur_pos): + if self.seen((cur_pos, dir_index)): + return True + + next_pos = cur_pos + DIRECTIONS[dir_index] + while grid.get(next_pos): + dir_index = (dir_index + 1) % len(DIRECTIONS) + next_pos = cur_pos + DIRECTIONS[dir_index] + + cur_pos = next_pos + + return False + def part1(self) -> Any: grid, cur_pos = self.parse_input() - return len(set(x[0] for x in walk_room(grid, cur_pos)[0])) + self.walk_room(grid, cur_pos) + return len(set(x[0] for x in self.SEEN)) def part2(self) -> Any: grid, start = self.parse_input() - visits = set(x[0] for x in walk_room(grid, start)[0]) + self.walk_room(grid, start) + visits = set(x[0] for x in self.SEEN) loops = 0 for obs_pos in visits: @@ -58,7 +58,7 @@ class Day(AOCDay): continue grid.set(obs_pos, True) - loops += walk_room(grid, start)[1] + loops += self.walk_room(grid, start) grid.set(obs_pos, False) return loops