Optimized 2024/07 P2 a little bit

This commit is contained in:
FrederikBaerentsen 2024-12-07 21:08:29 +01:00
parent 658dd6bc14
commit 966ee18b31
3 changed files with 10 additions and 27 deletions

View File

@ -1,8 +1,9 @@
#!/bin/python3
import sys,re
import sys, time ,re
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int,get_re,nprint,lprint
start_time = time.time()
input_f = 'input'
@ -18,6 +19,8 @@ def loadFile(input_f):
# and i use instructions[int(a[0])] = list2int(b)
# the line with 360: 8 3 7 4 1 is not used in the
# for loop that runs through all the instructions.
# This is because two items are 360 and dicts need
# distinct keys.
instructions = []
@ -33,7 +36,7 @@ def loadFile(input_f):
if part == 1:
def calculateResult(a:int,b:list,result:int):
if not b:
return result if result == a else 0
@ -56,12 +59,14 @@ if part == 1:
if part == 2:
def calculateResult2(a:int,b:list,result:int):
if result > a: # If the current result is more than out goal, return 0
return 0
if not b:
return result if result == a else 0
add = calculateResult2(a,b[1:],b[0]+result)
mul = calculateResult2(a,b[1:],b[0]*result)
# Issues happened when i did b[0]||result. Reversing it
# gave me the right result.
con = calculateResult2(a,b[1:],int(str(result)+str(b[0])))
@ -71,7 +76,8 @@ if part == 2:
result = 0
for idx,i in enumerate(instructions):
print('Line',(idx+1),i)
#print('Line',(idx+1),i)
result += calculateResult2(instructions[idx][0],instructions[idx][1],0)
print(result)
print("--- %s seconds ---" % (time.time() - start_time))

View File

@ -1,23 +0,0 @@
import sys
file = open(sys.argv[1]).read()
lines = [line.split(": ") for line in file.splitlines()]
lines = [(int(test), list(map(int, args.split()))) for test, args in lines]
star, plus, concat = lambda x, y: x * y, lambda x, y: x + y, lambda x, y: int(f"{x}{y}")
def solve(targ, args, operators):
def inner(targ, args, curr):
if curr > targ:
return False
match args:
case []:
return curr == targ
case [arg, *rest]:
return any(inner(targ, rest, op(curr, arg)) for op in operators)
return inner(targ, args[1:], args[0])
print(sum(targ for targ, args in lines if solve(targ, args, [star, plus])))
print(sum(targ for targ, args in lines if solve(targ, args, [star, plus, concat])))

Binary file not shown.