Advertisement
hhoppe

Advent of code 2023 day 10 fast

Dec 11th, 2023 (edited)
864
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. def day10(s, *, part2=False):  # Interior test using row intersection counting.
  2.   grid = np.array([list(line) for line in s.splitlines()])
  3.   ((y, x),) = np.argwhere(grid == 'S')
  4.   loop: list[tuple[int, int]] = []
  5.   dy, dx = 1, 0  # The start has a downward loop arm in all the examples I see.
  6.   while (ch := grid[y, x]) != 'S' or not loop:
  7.     loop.append((y, x))
  8.     dy, dx = (dx, dy) if ch in 'L7' else (-dx, -dy) if ch in 'JF' else (dy, dx)
  9.     y, x = y + dy, x + dx
  10.  
  11.   if not part2:
  12.     return len(loop) // 2
  13.  
  14.   loop_mask = np.full(grid.shape, False)
  15.   loop_mask[tuple(np.array(loop).T)] = True
  16.   lookup = np.array([chr(i) in '|LJ' for i in range(256)])
  17.   is_wall = lookup[grid.view(np.uint32)]  # ('U1' and uint32 have the same bitwidth.)
  18.   is_wall[~loop_mask] = 0
  19.   count = is_wall.cumsum(1) % 2
  20.   count[loop_mask] = 0
  21.   return count.sum()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement