hhoppe

Advent of code 2020 day 11

Dec 11th, 2020 (edited)
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. def grid_from_string(s):
  2.   return np.array(list(map(list, s.strip('\n').split('\n'))))
  3.  
  4. def count_steady_state_occupied1(s):
  5.   grid = grid_from_string(s)
  6.   shape = grid.shape
  7.   while True:
  8.     prev = grid.copy()
  9.     for y in range(shape[0]):
  10.       for x in range(shape[1]):
  11.         num_adjacent_occupied = 0
  12.         for y2 in range(max(0, y - 1), min(shape[0], y + 2)):
  13.           for x2 in range(max(0, x - 1), min(shape[1], x + 2)):
  14.             num_adjacent_occupied += ((y2 != y or x2 != x) and
  15.                                       prev[y2, x2] == '#')
  16.         if prev[y, x] == 'L' and num_adjacent_occupied == 0:
  17.           grid[y, x] = '#'
  18.         elif prev[y, x] == '#' and num_adjacent_occupied >= 4:
  19.           grid[y, x] = 'L'
  20.     if np.all(grid == prev):
  21.       return np.sum(grid == '#')
  22.  
  23. def count_steady_state_occupied2(s):
  24.   grid = grid_from_string(s)
  25.   shape = grid.shape
  26.   while True:
  27.     prev = grid.copy()
  28.     for y in range(shape[0]):
  29.       for x in range(shape[1]):
  30.         num_visible_occupied = 0
  31.         for dyx in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1),
  32.                     (1, 0), (1, 1)):
  33.           yx = (y, x)
  34.           while True:
  35.             yx = (yx[0] + dyx[0], yx[1] + dyx[1])
  36.             if not (0 <= yx[0] < shape[0] and 0 <= yx[1] < shape[1]):
  37.               break
  38.             if prev[yx] != '.':
  39.               num_visible_occupied += prev[yx] == '#'
  40.               break
  41.         if prev[y, x] == 'L' and num_visible_occupied == 0:
  42.           grid[y, x] = '#'
  43.         elif prev[y, x] == '#' and num_visible_occupied >= 5:
  44.           grid[y, x] = 'L'
  45.     if np.all(grid == prev):
  46.       return np.sum(grid == '#')
  47.  
Advertisement
Add Comment
Please, Sign In to add comment