AdventofCode2024/Day2/solution2.py

86 lines
2.5 KiB
Python
Raw Normal View History

2024-12-08 23:33:53 +01:00
#!/usr/bin/env python3
from typing import List
class Solution:
def __init__(self) -> None:
self.lines: List[str] = []
self.lines_split: List[List[str]] = []
self.lines_clean: List[List[int]] = []
self.result: int = 0
def read(self) -> None:
with open("input") as f:
self.lines = f.readlines()
def clean(self) -> None:
for i in range(len(self.lines)):
self.lines[i] = self.lines[i].strip()
def split_lines(self) -> None:
for i in range(len(self.lines)):
self.lines_split.append(self.lines[i].split())
def clean_lines(self) -> None:
for j in range(len(self.lines_split)):
tmp_list: List[int] = []
for i in range(len(self.lines_split[j])):
tmp_list.append(int(self.lines_split[j][i]))
self.lines_clean.append(tmp_list)
# This is an even uglier hack than in solution1. HACK: Make this look nicer.
def _is_safe(self, levels: List[int]) -> bool:
rate: int = 2137
unsafe_vals: int = 0
for i in range(len(levels) - 1):
if rate == 2137:
rate = 0
difference: int = levels[i] - levels[i+1]
if rate == 0:
if difference < 0:
rate = -1
elif difference > 0:
rate = 1
elif rate == 1:
if difference < 0:
if unsafe_vals != 1:
rate = -1
unsafe_vals += 1
elif rate == -1:
if difference > 0:
if unsafe_vals != 1:
rate = 1
unsafe_vals += 1
if unsafe_vals > 1:
return False
for i in range(len(levels) - 1):
rate: int = 0
difference: int = abs(levels[i+1] - levels[i])
if difference not in range(1,4):
unsafe_vals += 1
if unsafe_vals > 1:
return False
return True
def calculate_result(self) -> int:
for level in self.lines_clean:
if self._is_safe(level):
self.result += 1
return self.result
def main() -> None:
solver: Solution = Solution()
solver.read()
solver.clean()
solver.split_lines()
solver.clean_lines()
result: int = solver.calculate_result()
print(f"The amount of safe values is: {result}")
if __name__ == "__main__":
main()