feat: day 2 completed

This commit is contained in:
2024-12-02 12:41:39 +01:00
parent b318e1cdfd
commit 6f6387af4e
6 changed files with 1088 additions and 7 deletions

View File

@@ -2,4 +2,5 @@
See: https://adventofcode.com/2024 See: https://adventofcode.com/2024
- [Day 1: Historian Hysteria](day_1/README.md) - [Day 1: Historian Hysteria](day_1/README.md)
- [Day 2: Red-Nosed Reports](day_2/README.md)

3
day_2/README.md Normal file
View File

@@ -0,0 +1,3 @@
# --- Day 2: Red-Nosed Reports ---
See: https://adventofcode.com/2024/day/2

6
day_2/example.txt Normal file
View File

@@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

1000
day_2/input.txt Normal file

File diff suppressed because it is too large Load Diff

77
day_2/main.py Normal file
View File

@@ -0,0 +1,77 @@
from typing import List, TextIO
def read_input(f: TextIO) -> List[int]:
for line in f:
yield [int(n) for n in line.strip().split()]
def is_safe(report: List[int]) -> bool:
increasing = True
for j in range(0, len(report)):
n1, n2 = report[j], report[j + 1]
if n1 == n2:
return False
increasing = n2 > n1
break
for j in range(0, len(report)):
if j == len(report) - 1:
break
n1, n2 = report[j], report[j + 1]
if n1 == n2:
return False
if increasing and n1 > n2:
return False
if not increasing and n1 < n2:
return False
if 1 < abs(n2 - n1) > 3:
return False
return True
def count_safe_reports(f: TextIO) -> int:
total = 0
for report in read_input(f):
safe = is_safe(report)
if safe:
total += 1
return total
def count_safe_reports_with_tolerance(f: TextIO) -> int:
total = 0
for report in read_input(f):
safe = is_safe(report)
if not safe:
for n in range(1, len(report)+1):
safe = is_safe(report[0:n-1] + report[n:])
if safe:
break
if safe:
total += 1
return total
def main():
input_file = "input.txt"
with open(input_file, "r") as f:
print(f"safe_reports = {count_safe_reports(f)}")
with open(input_file, "r") as f:
print(f"safe_reports_with_tolerance = {count_safe_reports_with_tolerance(f)}")
if __name__ == "__main__":
main()

View File

@@ -1,6 +0,0 @@
def main():
print("Hello from aoc-2024!")
if __name__ == "__main__":
main()