Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2024-12-07 - Bridge Repair

(original .ipynb)

Day 7 puzzle input is a list of values followed by a sequence of "equations" that don't have any operators between them, mine is here). Part 1 involves inserting either addition or multiplication operators to make the equation compute the reading value. Part 2 involves doing the same but with the addition of a concatenation operator (where 1 || 2 gives 12)

puzzle_input_str = open("./puzzle_input/day7.txt").read()
test_input_str = """190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20"""


def parse_line(line):
    target_value, rest = line.split(": ")
    return [
        int(target_value),
        [int(s) for s in rest.split(" ")]
    ]


operations = (
    lambda a, b: a + b,
    lambda a, b: a * b,
)


def solve(target, total, values):
    if len(values) == 0:
        return target == total
    return any(
        solve(target, op(values[0], total), values[1:])
        for op in operations
    )

    
def part_one(input_str):
    equations = (parse_line(line) for line in input_str.splitlines())
    return sum(
        target
        for target, values
        in equations
        if solve(target, values[0], values[1:])
    )


assert 3749 == part_one(test_input_str)

print("part one:", part_one(puzzle_input_str))
part one: 7885693428401
operations = operations + (
    (lambda a, b: int(str(b) + str(a))),
)

    
def part_two(input_str):
    equations = (parse_line(line) for line in input_str.splitlines())
    return sum(
        target for target, values
        in equations
        if solve(target, values[0], values[1:])
    )


assert 11387 == part_two(test_input_str)

print("part two:", part_two(puzzle_input_str))
part two: 348360680516005