Skip to content

Commit

Permalink
Implement 2024 day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
bertptrs committed Dec 2, 2024
1 parent 443ff2c commit 5a96670
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 2024/src/aoc/days/day2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import numpy

from . import SeparateRunner


def _safe(nums: numpy.ndarray) -> bool:
steps = nums[1:] - nums[:-1]

if numpy.all(steps > 0):
return numpy.all((steps >= 1) & (steps <= 3))
elif numpy.all(steps < 0):
return numpy.all((steps <= -1) & (steps >= -3))
else:
return False


def is_safe(line: str) -> bool:
nums = numpy.fromstring(line, dtype=numpy.int32, sep=" ")

return _safe(nums)


def is_savable(line: str) -> bool:
nums = numpy.fromstring(line, dtype=numpy.int32, sep=" ")

return any(
_safe(numpy.concatenate((nums[:i], nums[i + 1 :]), axis=None))
for i in range(len(nums))
)


class DayRunner(SeparateRunner):
@classmethod
def part1(cls, data: str) -> int:
lines = data.strip().split("\n")

safe = sum(1 for line in lines if is_safe(line))

return safe

@classmethod
def part2(cls, data: str) -> int:
lines = data.strip().split("\n")

safe = sum(1 for line in lines if is_savable(line))

return safe
6 changes: 6 additions & 0 deletions 2024/tests/samples/02.txt
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions 2024/tests/test_day2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os

from aoc.days.day2 import DayRunner, is_savable


def get_data() -> str:
sample = os.path.dirname(__file__) + "/samples/02.txt"
with open(sample, mode="rt", encoding="utf-8") as f:
return f.read()


def test_individual_samples() -> None:
assert is_savable("7 6 4 2 1")
assert not is_savable("1 2 7 8 9")
assert not is_savable("9 7 6 2 1")
assert is_savable("1 3 2 4 5")
assert is_savable("8 6 4 4 1")
assert is_savable("1 3 6 7 9")


def test_sample_part1() -> None:
assert DayRunner.part1(get_data()) == 2


def test_sample_part2() -> None:
assert DayRunner.part2(get_data()) == 4

0 comments on commit 5a96670

Please sign in to comment.