Advertisement
hhoppe

Advent of code 2020 day 17

Dec 17th, 2020 (edited)
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. def apply_cycles(s, num_cycles=6, dim=3):
  2.   lines = s.strip('\n').split('\n')
  3.   indices = {
  4.       (0,) * (dim - 2) + (y, x)
  5.       for y, line in enumerate(lines) for x, ch in enumerate(line)
  6.       if ch == '#'
  7.   }
  8.   offsets = set(itertools.product(*((-1, 0, 1),) * dim)) - {(0,) * dim}
  9.  
  10.   def neighbors(index):
  11.     for offset in offsets:
  12.       yield tuple(map(sum, zip(index, offset)))
  13.  
  14.   def count_neighbors(index):
  15.     return sum(neighbor in indices for neighbor in neighbors(index))
  16.  
  17.   for _ in range(num_cycles):
  18.     survivors = {index for index in indices if 2 <= count_neighbors(index) <= 3}
  19.     adjacents = {neighbor for index in indices for neighbor in neighbors(index)}
  20.     births = {index for index in adjacents if count_neighbors(index) == 3}
  21.     indices = survivors | births
  22.  
  23.   return len(indices)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement