Advertisement
hhoppe

Advent of code 2024 day 22 all-generators

Dec 22nd, 2024 (edited)
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. def day22(s, *, part2=False):
  2.  
  3.   def generate_secrets(secret):
  4.     for _ in range(2001):
  5.       yield secret
  6.       secret = ((secret << 6) ^ secret) & 0xFFFFFF
  7.       secret = ((secret >> 5) ^ secret) & 0xFFFFFF
  8.       secret = ((secret << 11) ^ secret) & 0xFFFFFF
  9.  
  10.   def changes(secrets):
  11.     return (b % 10 - a % 10 for a, b in itertools.pairwise(secrets))
  12.  
  13.   initials = map(int, s.splitlines())
  14.  
  15.   if not part2:
  16.     return sum(more_itertools.last(generate_secrets(initial)) for initial in initials)
  17.  
  18.   totals: Any = collections.defaultdict(int)
  19.  
  20.   for initial in initials:
  21.     seen = set()
  22.     secrets = generate_secrets(initial)
  23.     it1, it2 = itertools.tee(secrets)
  24.     windows = more_itertools.windowed(changes(it1), 4)
  25.     scores = (secret % 10 for secret in itertools.islice(it2, 4, None))
  26.     for window, score in zip(windows, scores):
  27.       if window not in seen:
  28.         seen.add(window)
  29.         totals[window] += score
  30.  
  31.   return max(totals.values())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement