From: Pat Thoyts <pat.thoyts@gmail.com>
Date: Wed, 11 Dec 2024 15:01:30 +0000 (+0000)
Subject: day11: python
X-Git-Url: http://www.privyetmir.co.uk/gitweb?a=commitdiff_plain;h=HEAD;p=aoc2024.git

day11: python
---

diff --git a/day11/__init__.py b/day11/__init__.py
new file mode 100755
index 0000000..5267a80
--- /dev/null
+++ b/day11/__init__.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass
+from collections import defaultdict
+from typing import List, DefaultDict, TextIO
+
+
+@dataclass
+class Problem:
+    data: DefaultDict[int, int]
+
+    @staticmethod
+    def calc(value: int) -> List[int]:
+        if value == 0:
+            result = [1]
+        elif len(str(value)) % 2 == 0:
+            digits = str(value)
+            mid = len(digits) // 2
+            result = [int(digits[:mid]), int(digits[mid:])]
+        else:
+            result = [value * 2024]
+        return result
+
+    def run(self, count: int, debug: bool = False) -> int:
+        data = self.data
+        if debug:
+            print(data)
+        for _ in range(count):
+            newdata: DefaultDict[int, int] = defaultdict(int)
+            for value, count in data.items():
+                for newval in Problem.calc(value):
+                    newdata[newval] += count
+            if debug:
+                print(newdata)
+            data = newdata
+        return sum(data.values())
+
+    @staticmethod
+    def from_stream(stream: TextIO) -> 'Problem':
+        line = next(stream).strip()  # just one line
+        data = defaultdict(int, {int(x): 1 for x in line.split(' ')})
+        return Problem(data)
diff --git a/day11/__main__.py b/day11/__main__.py
new file mode 100644
index 0000000..1a86a6f
--- /dev/null
+++ b/day11/__main__.py
@@ -0,0 +1,21 @@
+import sys
+import argparse
+from . import Problem
+
+
+def main(args=None):
+    parser = argparse.ArgumentParser(description="AOC 2024 day 11")
+    parser.add_argument('filename', type=str)
+    parser.add_argument('-d', '--debug', action='store_true')
+    parser.add_argument('-c', '--count', type=int, default=25)
+    options = parser.parse_args(args)
+
+    with open(options.filename) as f:
+        problem = Problem.from_stream(f)
+
+    print(f"result {problem.run(options.count, debug=options.debug)}")
+    return 0
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv[1:]))