From c54b92ebc99f65d914f9b331843dfc788103b5d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Ytterstr=C3=B6m?= Date: Tue, 14 Dec 2021 07:03:44 +0100 Subject: [PATCH] Solve 2021:14 "Extended Polymerization" part 1 Solves 10 fine, but is sigkilled when running 40. refactoring needed. --- 2021-python/solutions/day_14.py | 48 ++++++++++++++++++++++++++++ 2021-python/tests/test_day_14.py | 54 ++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 2021-python/solutions/day_14.py create mode 100644 2021-python/tests/test_day_14.py diff --git a/2021-python/solutions/day_14.py b/2021-python/solutions/day_14.py new file mode 100644 index 0000000..6422d99 --- /dev/null +++ b/2021-python/solutions/day_14.py @@ -0,0 +1,48 @@ +from solutions import BaseSolution +from collections import Counter + + +class Solution(BaseSolution): + input_file = "14.txt" + + def __str__(self): + return "Day 14: Extended Polymerization" + + def parse_input(self, data): + p, tv = data.strip().split("\n\n") + return p, [tuple(r.strip().split(" -> ")) for r in tv.splitlines()] + + def solve(self, puzzle_input): + return self._solve(puzzle_input, 10) + + def solve_again(self, puzzle_input): + return self._solve(puzzle_input, 40) + + def _solve(self, puzzle_input, steps=10): + polymer, pir = puzzle_input + pir = dict(pir) + 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) + + +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 +""" diff --git a/2021-python/tests/test_day_14.py b/2021-python/tests/test_day_14.py new file mode 100644 index 0000000..3818f4d --- /dev/null +++ b/2021-python/tests/test_day_14.py @@ -0,0 +1,54 @@ +import unittest + +from solutions.day_14 import Solution + + +class Day14TestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + self.puzzle_input = self.solution.parse_input( + """ + NNCB + +CH -> B +HH -> N +CB -> H +NH -> C +HB -> C +HC -> B +HN -> C +NN -> C +BH -> H +NC -> B +NB -> B +BN -> B +BB -> N +BC -> B +CC -> N +CN -> C + + """ + ) + + def test_parse_puzzle_input(self): + data = """ + NNCB + +CH -> B +HH -> N +CB -> H + """ + assert self.solution.parse_input(data) == ( + "NNCB", + [("CH", "B"), ("HH", "N"), ("CB", "H")], + ) + + def test_solve_first_part(self): + assert self.solution.solve(self.puzzle_input) == 1749 - 161 + + # def test_solve_second_part(self): + # assert self.solution.solve_again(self.puzzle_input) == True + + +if __name__ == "__main__": + unittest.main()