diff --git a/day2/run.py b/day2/run.py index 0108ef9..c3561b1 100644 --- a/day2/run.py +++ b/day2/run.py @@ -1,3 +1,4 @@ +from copy import deepcopy from typing import List EXAMPLE = """ @@ -29,18 +30,31 @@ class CheckLevels: def _part2(self) -> int: return len([val for val in self.get_safe(problem_damper=True) if val]) - def get_differences(self) -> List[List[int]]: - return [ - [val - line[i] for i, val in enumerate(line[1:])] for line in self.levels - ] + @staticmethod + def get_differences(line) -> List[List[int]]: + return [val - line[i] for i, val in enumerate(line[1:])] def get_safe(self, problem_damper: bool = False) -> List[List[bool]]: - outp = [] - for line in self.get_differences(): + def is_level_safe(line: List[int]) -> bool: all_same = all([val < 0 for val in line]) or all([val > 0 for val in line]) - all_ge_1 = min([abs(val) for val in line]) >= 1 - all_le_3 = max([abs(val) for val in line]) <= 3 - outp.append(all_same and all_ge_1 and all_le_3) + all_in_range = ( + min([abs(val) for val in line]) >= 1 + and max([abs(val) for val in line]) <= 3 + ) + return all_same and all_in_range + + outp = [] + for line in self.levels: + safe = is_level_safe(self.get_differences(line)) + if problem_damper and not safe: + for i in range(len(line)): + reduced = deepcopy(line) + reduced.pop(i) + reduced_safe = is_level_safe(self.get_differences(reduced)) + if reduced_safe: + safe = reduced_safe + break + outp.append(safe) return outp