From b5425025a6b76b8e867569c5f902a385020de188 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Mon, 2 Dec 2024 10:24:02 +0000 Subject: [PATCH] 2024: d02: ex2: add solution --- 2024/d02/ex2/ex2.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100755 2024/d02/ex2/ex2.py diff --git a/2024/d02/ex2/ex2.py b/2024/d02/ex2/ex2.py new file mode 100755 index 0000000..c1a4b7b --- /dev/null +++ b/2024/d02/ex2/ex2.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python + +import sys +import itertools + +Report = list[int] + + +def solve(input: list[str]) -> int: + def parse(input: list[str]) -> list[Report]: + return [[int(n) for n in line.split()] for line in input] + + def is_safe(report: Report) -> bool: + def is_increasing_safe(report: Report): + for a, b in itertools.pairwise(report): + if a >= b: + return False + if not 1 <= (b - a) <= 3: + return False + return True + + return is_increasing_safe(report) or is_increasing_safe(report[::-1]) + + # Dampening by brute force + def is_dampened_safe(report: Report) -> bool: + for i in range(len(report)): + dampened_report = report[:i] + report[i + 1 :] + if is_safe(dampened_report): + return True + return False + + return sum(is_dampened_safe(report) for report in parse(input)) + + +def main() -> None: + input = sys.stdin.read().splitlines() + print(solve(input)) + + +if __name__ == "__main__": + main()