Advent of Code 2024 - Day 7

# Part 1

 1from __future__ import annotations
 2
 3import typing
 4
 5
 6def get_data(path: str) -> typing.Iterable[tuple[int, list[int]]]:
 7    with open(path) as f:
 8        for line in f:
 9            line = line.strip()
10            goal, nums = line.split(":")
11            yield int(goal), [int(n) for n in nums.strip().split()]
12
13
14def is_match(goal: int, inputs: list[int]) -> bool:
15    #
16    # Set the initial start point
17    #
18    stack: list[tuple[int, int]]= [(inputs[0], 1)]
19    while stack:
20        cur, depth = stack.pop()
21        #
22        # We've exhausted the inputs
23        #
24        if depth == len(inputs):
25            # We've reach our goal, celebrate
26            if cur == goal:
27                return True
28            # We aren't yet at the goal, this path was a failure
29            else:
30                continue
31
32        #
33        # We've overshot no point in continuing down this path.
34        #
35        if cur > goal:
36            continue
37
38        stack.append((cur * inputs[depth], depth + 1))
39        stack.append((cur + inputs[depth], depth + 1))
40
41    return False
42
43
44def main(data: typing.Iterable[tuple[int, list[int]]]) -> int:
45    output = 0
46    for goal, inputs in data:
47        if is_match(goal, inputs):
48            output += goal
49
50    return output
51
52
53if __name__ == '__main__':
54    print(main(get_data("day_7_input.txt")))

# Part 2

 1def get_data(path):
 2    with open(path) as f:
 3        for line in f:
 4            line = line.strip()
 5            goal, nums = line.split(":")
 6            yield int(goal), [int(n) for n in nums.strip().split()]
 7
 8
 9def is_match(goal, inputs):
10    stack = [(inputs[0], 1)]
11    while stack:
12        cur, depth = stack.pop()
13        if depth == len(inputs):
14            if cur == goal:
15                return True
16            else:
17                continue
18        if cur > goal:
19            continue
20
21        stack.append((cur * inputs[depth], depth + 1))
22        stack.append((cur + inputs[depth], depth + 1))
23        stack.append((int(str(cur) + str(inputs[depth])), depth + 1))
24
25    return False
26
27
28def main(data) -> int:
29    output = 0
30    for goal, inputs in data:
31        if is_match(goal, inputs):
32            output += goal
33    return output
34
35
36if __name__ == '__main__':
37    print(main(get_data("day_7_input.txt")))