Add day 2 part 2

This commit is contained in:
Evie Litherland-Smith 2024-12-09 07:04:34 +00:00
parent 4778aacf8e
commit 674ddab111

View file

@ -1,3 +1,4 @@
from copy import deepcopy
from typing import List from typing import List
EXAMPLE = """ EXAMPLE = """
@ -29,18 +30,31 @@ class CheckLevels:
def _part2(self) -> int: def _part2(self) -> int:
return len([val for val in self.get_safe(problem_damper=True) if val]) return len([val for val in self.get_safe(problem_damper=True) if val])
def get_differences(self) -> List[List[int]]: @staticmethod
return [ def get_differences(line) -> List[List[int]]:
[val - line[i] for i, val in enumerate(line[1:])] for line in self.levels return [val - line[i] for i, val in enumerate(line[1:])]
]
def get_safe(self, problem_damper: bool = False) -> List[List[bool]]: def get_safe(self, problem_damper: bool = False) -> List[List[bool]]:
outp = [] def is_level_safe(line: List[int]) -> bool:
for line in self.get_differences():
all_same = all([val < 0 for val in line]) or all([val > 0 for val in line]) 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_in_range = (
all_le_3 = max([abs(val) for val in line]) <= 3 min([abs(val) for val in line]) >= 1
outp.append(all_same and all_ge_1 and all_le_3) 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 return outp