14.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from util import get_input
  2. from more_itertools import sliding_window as sw
  3. from more_itertools import flatten
  4. from itertools import product
  5. input = get_input("14.input")
  6. template = input[0]
  7. rules = {a: b for [a, b] in [line.split(" -> ") for line in input[2:]]}
  8. all_pairs = list(product(list(set(flatten([c for c in rules.values()]))), repeat=2))
  9. all_pairs = [a + b for (a, b) in all_pairs]
  10. def step(pairs, rules, counts):
  11. next = {k: 0 for k in all_pairs}
  12. for (k, v) in pairs.items():
  13. if k in rules:
  14. [a, c] = k
  15. b = rules[k]
  16. next[a + b] += v
  17. next[b + c] += v
  18. counts[b] += v
  19. else:
  20. next[k] += v
  21. return next
  22. def run(template, rules, steps):
  23. pairs = {k: 0 for k in all_pairs}
  24. for [a, b] in sw(template, 2):
  25. pairs[a + b] += 1
  26. counts = {k: 0 for k in set(rules.values())}
  27. for c in template:
  28. counts[c] += 1
  29. for _ in range(steps):
  30. pairs = step(pairs, rules, counts)
  31. return max(counts.values()) - min(counts.values())
  32. print("Part 1:", run(template, rules, 10))
  33. print("Part 2:", run(template, rules, 40))