Skip to content

Commit c871a9e

Browse files
committed
Implement 2024 day 7
1 parent 0c7c54b commit c871a9e

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

2024/src/aoc/days/day7.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from . import SeparateRunner
2+
3+
4+
def parse_input(input: str) -> tuple[int, list[int]]:
5+
result = []
6+
7+
for line in input.strip().split("\n"):
8+
test, nums = line.split(": ")
9+
result.append((int(test), list(map(int, nums.split(" ")))))
10+
11+
return result
12+
13+
14+
def is_possible(target: int, nums: list[int], cur: int) -> bool:
15+
if cur == target and not nums:
16+
return True
17+
18+
if cur > target or not nums:
19+
return False
20+
21+
head = nums[0]
22+
remainder = nums[1:]
23+
24+
return is_possible(target, remainder, cur + head) or is_possible(
25+
target, remainder, cur * head
26+
)
27+
28+
29+
def is_possible2(target: int, nums: list[int], cur: int) -> bool:
30+
if cur == target and not nums:
31+
return True
32+
33+
if cur > target or not nums:
34+
return False
35+
36+
head = nums[0]
37+
remainder = nums[1:]
38+
39+
return (
40+
is_possible2(target, remainder, cur + head)
41+
or is_possible2(target, remainder, cur * head)
42+
or is_possible2(target, remainder, int(f"{cur}{head}"))
43+
)
44+
45+
46+
class DayRunner(SeparateRunner):
47+
@classmethod
48+
def part1(cls, input: str) -> int:
49+
lines = parse_input(input)
50+
51+
return sum(
52+
target for target, nums in lines if is_possible(target, nums[1:], nums[0])
53+
)
54+
55+
@classmethod
56+
def part2(cls, input: str) -> int:
57+
lines = parse_input(input)
58+
59+
return sum(
60+
target for target, nums in lines if is_possible2(target, nums[1:], nums[0])
61+
)

2024/tests/samples/07.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
190: 10 19
2+
3267: 81 40 27
3+
83: 17 5
4+
156: 15 6
5+
7290: 6 8 6 15
6+
161011: 16 10 13
7+
192: 17 8 14
8+
21037: 9 7 18 13
9+
292: 11 6 16 20

2024/tests/test_day07.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import os
2+
3+
from aoc.days.day7 import DayRunner
4+
5+
6+
def get_data() -> str:
7+
sample = os.path.dirname(__file__) + "/samples/07.txt"
8+
with open(sample, mode="rt", encoding="utf-8") as f:
9+
return f.read()
10+
11+
12+
def test_sample_part1() -> None:
13+
assert DayRunner.part1(get_data()) == 3749
14+
15+
16+
def test_sample_part2() -> None:
17+
assert DayRunner.part2(get_data()) == 11387

0 commit comments

Comments
 (0)