advent-of-code-2024/day7.1.py

46 lines
990 B
Python
Raw Permalink Normal View History

2024-12-07 19:12:58 -08:00
""" day 7 part 1 """
import fileinput
import typing
def has_solution(goal, operands):
# print(f'goal={goal} operands={operands}')
if len(operands) == 0:
return ''
if len(operands) == 1:
# print(f'{goal} == {operands[0]}?')
return goal if goal == operands[0] else ''
# check add
here = operands[-1]
subgoal = operands[:-1]
if prev := has_solution(goal - here, subgoal):
# print(f'{goal - here} + {here}?')
return f'{prev} + {here}'
if prev := not here or has_solution(goal / here, subgoal):
# print(f'{goal / here} * {here}?')
return f'{prev} * {here}'
return ''
count = 0
for line in fileinput.input():
goal, _, expr = line.strip().partition(':')
# print(f'{goal} - {expr}')
goal = int(goal)
operands = [int(term) for term in expr.strip().split()]
solution = has_solution(goal, operands)
if solution:
print(solution)
count += goal
print(count)