diff --git a/2021-python/solutions/day_14.py b/2021-python/solutions/day_14.py index 6422d99..faee97b 100644 --- a/2021-python/solutions/day_14.py +++ b/2021-python/solutions/day_14.py @@ -1,5 +1,5 @@ from solutions import BaseSolution -from collections import Counter +from collections import Counter, defaultdict class Solution(BaseSolution): @@ -21,28 +21,23 @@ class Solution(BaseSolution): def _solve(self, puzzle_input, steps=10): polymer, pir = puzzle_input pir = dict(pir) + pairs = defaultdict(int) + chars = defaultdict(int, Counter(polymer)) + for l, r in zip(polymer[:-1], polymer[1:]): + pairs[(l, r)] += 1 for _ in range(steps): - p = [] - for i in range(len(polymer) - 1): - a, b = polymer[i : i + 2] - p.append(a) - s = pir.get(a + b) - if s: - p.append(s) - p.append(polymer[-1]) - polymer = p - c = [v for k, v in Counter(polymer).most_common()] - return max(c) - min(c) + nxt = defaultdict(int) + for lr, count in pairs.items(): + l, r = lr + m = pir["".join(lr)] + nxt[(l, m)] += count + nxt[(m, r)] += count + chars[m] += count + pairs = nxt + cv = chars.values() + return max(cv) - min(cv) if __name__ == "__main__": solution = Solution() solution.show_results() - -""" -Template: NNCB -After step 1: NCNBCHB -After step 2: NBCCNBBBCBHCB -After step 3: NBBBCNCCNBBNBNBBCHBHHBCHB -After step 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB -"""