Advertisement
hhoppe

Advent of code 2020 day 24

Dec 23rd, 2020 (edited)
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. def process(s, num_days=0):
  2.   offsets = dict(e=(0, 1), w=(0, -1), sw=(1, 0), se=(1, 1),
  3.                  nw=(-1, -1), ne=(-1, 0))
  4.   indices = set()
  5.   for line in s.strip('\n').splitlines():
  6.     index = (0, 0)
  7.     while line:
  8.       for prefix, offset in offsets.items():
  9.         if line.startswith(prefix):
  10.           index = tuple(map(sum, zip(index, offset)))
  11.           line = line[len(prefix):]
  12.     indices ^= {index}
  13.  
  14.   def neighbors(index):
  15.     for offset in offsets.values():
  16.       # yield tuple(map(sum, zip(index, offset)))  # 2x slower
  17.       yield index[0] + offset[0], index[1] + offset[1]
  18.  
  19.   for _ in range(num_days):
  20.     neighbor_counts = collections.Counter(
  21.         itertools.chain.from_iterable(neighbors(index) for index in indices))
  22.     indices = {index for index, count in neighbor_counts.items()
  23.                if count == 2 or count == 1 and index in indices}
  24.  
  25.   return len(indices)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement