From 905dddaf66339e807c2b29d633d5eade63b62ac7 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Thu, 10 Dec 2020 00:05:39 +0100 Subject: [PATCH] 9 --- solutions/9/README.md | 11 +++++++++ solutions/9/python/main.py | 50 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 solutions/9/README.md create mode 100644 solutions/9/python/main.py diff --git a/solutions/9/README.md b/solutions/9/README.md new file mode 100644 index 0000000..4f4468e --- /dev/null +++ b/solutions/9/README.md @@ -0,0 +1,11 @@ +# 9 + +Again the python std lib saved me some lines of code. `itertools` to the rescue and basically we are done. + +
+ Solutions +
    +
  1. 23278925
  2. +
  3. 4011064
  4. +
+
diff --git a/solutions/9/python/main.py b/solutions/9/python/main.py new file mode 100644 index 0000000..f863b47 --- /dev/null +++ b/solutions/9/python/main.py @@ -0,0 +1,50 @@ +from os.path import join, dirname +from typing import List, Optional, Set, Tuple +from itertools import combinations + + +class XMAS: + + def __init__(self, data: str, size: int) -> None: + self.size: int = size + self.position: int = size + self.buffer: List[int] = [ + int(x) + for x in data.strip().split('\n') + ] + + def check_next(self) -> bool: + possible = [ + a + b + for a, b in combinations(self.buffer[self.position - self.size: self.position], 2) + ] + return self.buffer[self.position] in possible + + def find_first_invalid(self) -> int: + l = len(self.buffer) + while self.position < l: + valid = self.check_next() + if not valid: + return self.buffer[self.position] + self.position += 1 + raise Exception + + def find_slice(self, target: int): + l = len(self.buffer) + for n in range(l): + for m in range(n, l): + slice = self.buffer[n: m] + if sum(slice) == target: + return min(slice) + max(slice) + raise Exception + + +data = join(dirname(__file__), '../data.txt') +with open(data) as f: + xmas = XMAS(f.read(), 25) + + first_invalid = xmas.find_first_invalid() + print(first_invalid) + + solution = xmas.find_slice(first_invalid) + print(solution)