/ Python / 2021 / 14.py
14.py
 1  from lib import *
 2  
 3  input = read_input(2021, 14)
 4  
 5  lines = input.splitlines()
 6  
 7  
 8  def solve(n):
 9      adj = collections.Counter(sliding_window(lines[0]))
10      rules = dict(line.split(" -> ") for line in lines[2:])
11      for _ in range(n):
12          new = collections.Counter()
13          for (a, b), c in adj.items():
14              if x := rules.get(a + b):
15                  new[(a, x)] += c
16                  new[(x, b)] += c
17              else:
18                  new[(a, b)] += c
19          adj = new
20  
21      chars = collections.Counter(lines[0][0])
22      for (_, b), c in adj.items():
23          chars[b] += c
24  
25      a, b = minmax(chars.values())
26      return b - a
27  
28  
29  print(solve(10))
30  print(solve(40))