Created
December 7, 2024 18:56
-
-
Save rodrigogiraoserrao/e3eb0faa259a51c9f457237a7dbc1517 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# === Parsing === | |
equations = [] | |
with open("input.txt", "r") as f: | |
for line in f: | |
target, _, operands = line.partition(":") | |
equations.append( | |
( | |
int(target), | |
[int(num) for num in operands.split()], | |
) | |
) | |
print(equations) | |
print(equations[-1]) | |
# === Part 1 === | |
from itertools import product | |
from operator import add, mul | |
operator_options = [add, mul] | |
total = 0 | |
for target, operands in equations: | |
all_operator_combinations = product( | |
operator_options, | |
repeat=len(operands) - 1, | |
) | |
for operator_combination in all_operator_combinations: | |
partial_result = operands[0] | |
for operand, operator in zip(operands[1:], operator_combination): | |
partial_result = operator(partial_result, operand) | |
if partial_result == target: | |
total += target | |
break | |
print(total) | |
# === Part 2 === | |
from itertools import product | |
from operator import add, mul | |
operator_options = [ | |
add, | |
mul, | |
lambda x, y: int(f"{x}{y}"), | |
] | |
import time | |
""" | |
start = time.perf_counter() | |
total = 0 | |
for target, operands in equations: | |
all_operator_combinations = product( | |
operator_options, | |
repeat=len(operands) - 1, | |
) | |
for operator_combination in all_operator_combinations: | |
partial_result = operands[0] | |
for operand, operator in zip(operands[1:], operator_combination): | |
partial_result = operator(partial_result, operand) | |
if partial_result == target: | |
total += target | |
break | |
end = time.perf_counter() | |
print(f"Got solution in {end - start}") | |
print(total) | |
""" | |
# === Part 2, take 2 === | |
def is_valid(target, operands): | |
if len(operands) == 1: | |
return target == operands[0] | |
elif not operands: | |
return False | |
last_op = operands[-1] | |
tail = operands[:-1] | |
if str(target).endswith(str(last_op)): # concatenation | |
if is_valid(target // pow(10, len(str(last_op))), tail): | |
return True | |
if target % last_op == 0: # multiplication | |
if is_valid(target // last_op, tail): | |
return True | |
if target > last_op: | |
if is_valid(target - last_op, tail): # addition | |
return True | |
return False | |
start = time.perf_counter() | |
total = 0 | |
for target, operands in equations: | |
if is_valid(target, operands): | |
total += target | |
end = time.perf_counter() | |
print(f"Got solution in {end - start}") | |
print(total) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment