diff --git a/2024/7/script.py b/2024/7/script.py index 64f9d9f..f5c849d 100644 --- a/2024/7/script.py +++ b/2024/7/script.py @@ -1,21 +1,28 @@ from GhostyUtils import aoc import operator import itertools +from typing import Iterable, Callable -def calibrate(target, operands, operators) -> int: +def calibrate(target: int, operands: list[int], operators: Iterable[Callable]) -> int: + # try all operators in all positions between operands for ops in itertools.product(operators, repeat=len(operands)-1): + # calculate left-to-right result = operands[0] for i, op in enumerate(ops): result = op(result, operands[i+1]) # print(f"{target}: {operands} -> {result} | {ops}") + # return early if we find a calculation that works if result == target: return target + + # no valid calculation found return 0 +# concatenate two ints as if they were strings def concat(l: int, r: int) -> int: return int(f"{l}{r}") @@ -25,6 +32,7 @@ def main(): total = 0 p2total = 0 + for line in inputs: target, operands = line.split(': ') target = int(target) @@ -32,8 +40,10 @@ def main(): result = calibrate(target, operands, [operator.add, operator.mul]) total += result + if result == 0: p2total += calibrate(target, operands, [operator.add, operator.mul, concat]) + print(f"p1: {total}") print(f"p2: {total+p2total}")