day 7 optimization

instead of lists, construct a tower of nested generators. i think this
is equivalent to a recursive backtracking solution.

since the input doesn't contain 0 we can check for <goal in the
intermediate layers, and ==goal at the end.
main
magical 2024-12-07 21:02:18 +00:00
parent 9e083f00f9
commit 7373859412
1 changed files with 17 additions and 26 deletions

View File

@ -6,38 +6,29 @@ def solve(file):
goal = int(nums[0].rstrip(":"))
nums = [int(x) for x in nums[1:]]
if viable(goal, nums):
if viable(goal, nums, lambda n,x: (n*x, n+x)):
t += goal
elif viable2(goal, nums):
elif viable(goal, nums, lambda n,x: (n*x, n+x, int(str(n)+str(x)))):
t2 += goal
print(t)
print(t+t2)
def viable(goal, nums):
def viable(goal, nums, combine):
candidates = [nums[0]]
next = []
for x in nums[1:]:
for n in candidates:
for m in n*x, n+x:
if m <= goal:
next.append(m)
next, candidates = candidates, next
next.clear()
#print(goal, nums, candidates, goal in candidates)
return goal in candidates
def viable2(goal, nums):
candidates = [nums[0]]
next = []
for x in nums[1:]:
for n in candidates:
for m in n*x, n+x, int(str(n)+str(x)):
if m <= goal: #and m not in next:
next.append(m)
next, candidates = candidates, next
next.clear()
print(goal, nums, len(candidates), goal in candidates)
return goal in candidates
for x in nums[1:-1]:
candidates = (lambda C, x: (
m
for n in C
for m in combine(n,x)
if m < goal
))(candidates, x)
#candidates = list(candidates); print(len(candidates))
x = nums[-1]
for n in candidates:
for m in combine(n,x):
if m == goal:
return True
return False
solve(open('sample1.in'))
solve(open('input'))