diff options
Diffstat (limited to '2024/aoc2024-d07.py')
-rw-r--r-- | 2024/aoc2024-d07.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/2024/aoc2024-d07.py b/2024/aoc2024-d07.py new file mode 100644 index 0000000..46a594d --- /dev/null +++ b/2024/aoc2024-d07.py @@ -0,0 +1,40 @@ +#advent of code 2024 +#day 07 +#rewritten to do both parts at the same time +#very slow solution (roughly 10 mins of runtime) +#it generates all possible arrangements of operators +#to fill in the empty spaces in the equation +#on top of that, it utilizes eval() +#however, the solution works and that's the important part + +import itertools + +def calculate(test,nums,ops): + N = [n for n in nums.split(" ")]; + ValidAnswerP1 = False; + ValidAnswerP2 = False; + for prod in itertools.product(ops,repeat=nums.count(" ")): + score = ''+N[0]; + for i,p in enumerate(prod): + if p == "||": p = ""; + teststring = str(score) + p + N[i+1]; + score = eval(teststring); + if score == test: + ValidAnswerP2 = True; + if "||" not in prod: ValidAnswerP1 = True; + if ValidAnswerP1 and ValidAnswerP2: break; + return ValidAnswerP1, ValidAnswerP2; + +part1 = 0; +part2 = 0; +ops = ["+","*","||"]; +f = open("07.ex","r"); +for l in f: + TestValue, numbers = l[:-1].split(": "); + TestValue = int(TestValue); + valid_p1, valid_p2 = calculate(TestValue, numbers,ops); + part1 += valid_p1*TestValue; + part2 += valid_p2*TestValue; +f.close(); +print("part 1 = ", part1); +print("part 2 = ", part2); |