advent-of-code/2024/python/day02.py

70 lines
1.5 KiB
Python
Raw Normal View History

2024-12-04 02:03:33 +00:00
import matrix
import shared
import itertools
import functools
2024-12-04 15:19:43 +00:00
2024-12-04 02:03:33 +00:00
def is_increasing(sequence):
2024-12-04 15:19:43 +00:00
return all(sequence[i] < sequence[i + 1] for i in range(len(sequence) - 1))
2024-12-04 02:03:33 +00:00
def is_decreasing(sequence):
2024-12-04 15:19:43 +00:00
return all(sequence[i] > sequence[i + 1] for i in range(len(sequence) - 1))
2024-12-04 02:03:33 +00:00
def parse_line(row):
for previous, current in zip(row, row[1:]):
2024-12-04 02:37:32 +00:00
diff = abs(current - previous)
2024-12-04 02:03:33 +00:00
if diff >= 1 and diff <= 3:
continue
2024-12-04 02:37:32 +00:00
return 0
2024-12-04 15:19:43 +00:00
if not (is_increasing(row) or is_decreasing(row)):
2024-12-04 02:37:32 +00:00
return 0
return 1
2024-12-04 02:03:33 +00:00
# @shared.profile
def part1(rows):
rows = [list(map(int, row.split())) for row in rows]
safe = 0
for row in rows:
2024-12-04 02:37:32 +00:00
safe += parse_line(row)
2024-12-04 02:03:33 +00:00
print(safe)
2024-12-04 02:37:32 +00:00
def brute_force(row):
check = parse_line(row)
if check == 1:
return 1
for x in range(len(row)):
2024-12-04 15:19:43 +00:00
new_row = row[:x] + row[x + 1 :]
2024-12-04 02:37:32 +00:00
check = parse_line(new_row)
if check == 1:
return 1
return 0
2024-12-04 02:03:33 +00:00
# @shared.profile
def part2(rows):
2024-12-04 02:04:02 +00:00
rows = [list(map(int, row.split())) for row in rows]
safe = 0
for row in rows:
2024-12-04 02:37:32 +00:00
safe += brute_force(row)
2024-12-04 02:04:02 +00:00
print(safe)
2024-12-04 02:03:33 +00:00
def main():
rows = [row for row in shared.load_rows(2)]
with shared.elapsed_timer() as elapsed:
part1(rows)
print("🕒", elapsed())
rows = [row for row in shared.load_rows(2, True)]
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()