Skip to content

Commit

Permalink
[2024/7] comments
Browse files Browse the repository at this point in the history
  • Loading branch information
StarlitGhost committed Dec 7, 2024
1 parent 096c0ec commit 7521067
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion 2024/7/script.py
Original file line number Diff line number Diff line change
@@ -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}")

Expand All @@ -25,15 +32,18 @@ def main():

total = 0
p2total = 0

for line in inputs:
target, operands = line.split(': ')
target = int(target)
operands = list(map(int, operands.split(' ')))

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}")

Expand Down

0 comments on commit 7521067

Please sign in to comment.