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
parent
9e083f00f9
commit
7373859412
43
day07/sol.py
43
day07/sol.py
|
@ -6,38 +6,29 @@ def solve(file):
|
||||||
goal = int(nums[0].rstrip(":"))
|
goal = int(nums[0].rstrip(":"))
|
||||||
nums = [int(x) for x in nums[1:]]
|
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
|
t += goal
|
||||||
elif viable2(goal, nums):
|
elif viable(goal, nums, lambda n,x: (n*x, n+x, int(str(n)+str(x)))):
|
||||||
t2 += goal
|
t2 += goal
|
||||||
print(t)
|
print(t)
|
||||||
print(t+t2)
|
print(t+t2)
|
||||||
|
|
||||||
def viable(goal, nums):
|
def viable(goal, nums, combine):
|
||||||
candidates = [nums[0]]
|
candidates = [nums[0]]
|
||||||
next = []
|
for x in nums[1:-1]:
|
||||||
for x in nums[1:]:
|
candidates = (lambda C, x: (
|
||||||
for n in candidates:
|
m
|
||||||
for m in n*x, n+x:
|
for n in C
|
||||||
if m <= goal:
|
for m in combine(n,x)
|
||||||
next.append(m)
|
if m < goal
|
||||||
next, candidates = candidates, next
|
))(candidates, x)
|
||||||
next.clear()
|
#candidates = list(candidates); print(len(candidates))
|
||||||
#print(goal, nums, candidates, goal in candidates)
|
x = nums[-1]
|
||||||
return goal in candidates
|
for n in candidates:
|
||||||
|
for m in combine(n,x):
|
||||||
def viable2(goal, nums):
|
if m == goal:
|
||||||
candidates = [nums[0]]
|
return True
|
||||||
next = []
|
return False
|
||||||
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
|
|
||||||
|
|
||||||
solve(open('sample1.in'))
|
solve(open('sample1.in'))
|
||||||
solve(open('input'))
|
solve(open('input'))
|
||||||
|
|
Loading…
Reference in New Issue