-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.py
62 lines (44 loc) · 1.33 KB
/
day02.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Advent of Code 2024, Day 2: Red-Nosed Reports.
See: https://adventofcode.com/2024/day/2
"""
import sys
from itertools import pairwise
from typing import TextIO
def parse(file: TextIO):
for line in file.readlines():
yield list(map(int, line.split()))
def is_valid(levels: list[int]):
return (sorted(levels) == levels or sorted(levels, reverse=True) == levels) and all(
1 <= abs(a - b) <= 3 for a, b in pairwise(levels)
)
def problem_dampener(levels: list[int]):
for i in range(len(levels)):
yield levels[:i] + levels[i + 1 :]
def part_one(file: TextIO) -> int:
"""
Solve part one of the puzzle.
"""
valid = list(levels for levels in parse(file) if is_valid(levels))
return len(valid)
def part_two(file: TextIO) -> int:
"""
Solve part two of the puzzle.
"""
valid = list(
levels
for levels in parse(file)
if any(is_valid(variant) for variant in problem_dampener(levels))
)
return len(valid)
def main():
"""
The main entrypoint for the script.
"""
filename = sys.argv[0].replace(".py", ".txt")
with open(filename, encoding="utf-8") as file:
print("Part one:", part_one(file))
with open(filename, encoding="utf-8") as file:
print("Part two:", part_two(file))
if __name__ == "__main__":
main()