advent_of_code_2024/day_02/program.py

63 lines
1.7 KiB
Python
Executable file

#!/usr/bin/env python3
# https://adventofcode.com/2024/day/2
def get_lines(filename: str) -> list:
with open(filename, "r") as file:
return [line.strip() for line in file.readlines()]
def get_report_entries(lines: list) -> list:
report_entries = []
for line in lines:
entry = [int(x) for x in line.split(" ")]
report_entries.append(entry)
return report_entries
def is_safe_single(reports: list) -> bool:
increasing = True
decreasing = True
for a, b in zip(reports, reports[1:]):
distance = abs(a - b)
if distance == 0 or distance > 3:
return False
if a > b:
increasing = False
if a < b:
decreasing = False
return increasing or decreasing
def is_safe_full(reports: list, dampener: bool) -> bool:
if is_safe_single(reports):
return True
if dampener:
for i in range(len(reports)):
if is_safe_single(reports[:i] + reports[i + 1:]):
return True
return False
def get_safe_reports(report_entries: list, dampener: bool) -> int:
safe_reports = 0
for entry in report_entries:
if is_safe_full(entry, dampener):
safe_reports += 1
return safe_reports
def main():
# lines = get_lines("sample-input.txt")
lines = get_lines("input.txt")
report_entries = get_report_entries(lines)
safe_reports = get_safe_reports(report_entries, dampener=False)
print(f"Part 1: There are {safe_reports} safe reports.")
safe_reports = get_safe_reports(report_entries, dampener=True)
print(f"Part 2: There are {safe_reports} safe reports.")
if __name__ == '__main__':
main()