1
0
Fork 0
adventofcode/2024/02/main.py

77 lines
1.7 KiB
Python
Raw Permalink Normal View History

2024-12-06 12:06:10 +00:00
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Author: Sebastian Mark
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
def readinput() -> list[int]:
reports = []
with open("input", "r", encoding="utf-8") as file:
for line in file:
levels = list(map(int, line.split(" ")))
reports.append(levels)
return reports
def is_valid_level_difference(i: int, j: int) -> bool:
if i == j:
return False
if abs(i - j) > 3:
return False
return True
def is_sorted(levels: list) -> bool:
asc_sorted = levels == sorted(levels)
desc_sorted = levels == sorted(levels, reverse=True)
return asc_sorted or desc_sorted
def is_save(levels: list) -> bool:
if not is_sorted(levels):
return False
for i in range(len(levels) - 1):
if not is_valid_level_difference(levels[i], levels[i + 1]):
return False
return True
def remove_level_by_index(levels: list, index: int) -> list:
copy = levels.copy()
copy.pop(index)
return copy
def is_save_with_damper(levels: list) -> bool:
if is_save(levels):
return True
for i in range(len(levels)):
if is_save(remove_level_by_index(levels, i)):
return True
return False
def main():
reports = readinput()
# part 1
save_count = sum(is_save(report) for report in reports)
print("Save reports: %d" % save_count)
# part 2
save_count = sum(is_save_with_damper(report) for report in reports)
print("Save reports (with damper): %d" % save_count)
if __name__ == "__main__":
main()