Skip to content

Commit

Permalink
day06 part2
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasrenault committed Dec 6, 2024
1 parent 3fdfb10 commit fdccf74
Showing 1 changed file with 30 additions and 9 deletions.
39 changes: 30 additions & 9 deletions advent/advent2024/day06.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,52 @@
def main():
lines = advent.get_input_lines()
grid = np.array([[c for c in line] for line in lines])
start = np.where(grid == "^")
start_position = np.where(grid == "^")
start = (start_position[0][0], start_position[1][0])

seen = run(grid, (start[0][0], start[1][0]))
advent.submit(1, len(seen))
looped, seen = run(grid, start)
unique = set([(x, y) for x, y, _ in seen])
advent.submit(1, len(unique))

count = 0
unique.remove(start)
for position in unique:
grid[position] = "#"
looped, _ = run(grid, start)
count += 1 if looped else 0
grid[position] = "."

advent.submit(2, count)


def print_grid(grid: npt.NDArray[np.str_]):
for row in range(grid.shape[0]):
print("".join(grid[row]))


def run(grid: npt.NDArray[np.str_], start: tuple[int, int]) -> set[tuple[int, int]]:
def run(
grid: npt.NDArray[np.str_], start: tuple[int, int]
) -> tuple[bool, set[tuple[int, int, int]]]:
x, y = start
dir = 0
seen: set[tuple[int, int]] = set()
seen.add((x, y))
seen: set[tuple[int, int, int]] = set()
dx, dy = deltas[dir]
while 0 <= x + dx < grid.shape[0] and 0 <= y + dy < grid.shape[1]:
while (
0 <= x + dx < grid.shape[0]
and 0 <= y + dy < grid.shape[1]
and (x, y, dir) not in seen
):
seen.add((x, y, dir))
dx, dy = deltas[dir]
if grid[(x + dx, y + dy)] == "#":
dir = (dir + 1) % 4
else:
x, y = x + dx, y + dy
seen.add((x, y))
return seen
if (x, y, dir) in seen:
return True, seen

seen.add((x, y, dir))
return False, seen


if __name__ == "__main__":
Expand Down

0 comments on commit fdccf74

Please sign in to comment.