Solve 2024:7 p1-2 "Bridge Repair"
Got thrown of big time at pt 1 since there is a duplicate test value in my puzzle input. The code initially asumed that all test values should be distinct. Biased from seeing "test" in the termology, most likely. Earlier editions of the code also tried to create all combinations using binary strings, but it fell short on pt 2 when a third operation was introduced. From some inspiration in the solutions mega thread on Reddit, the final code is queue-based instead. Apparently, I also learned this kind of problem is usually well suited for DFS search, and apparently the final code very much is _in deed_ a DFS.
This commit is contained in:
parent
7b2b101b8b
commit
81fe14a407
2 changed files with 45 additions and 2 deletions
|
|
@ -110,10 +110,10 @@ for i in [str(n).zfill(2) for n in range(1, 26)]:
|
|||
except AttributeError:
|
||||
pass
|
||||
if p1:
|
||||
print(f" 1. {p1}")
|
||||
print(f" 1) {p1}")
|
||||
stars += 1
|
||||
if p2:
|
||||
print(f" 2. {p2}")
|
||||
print(f" 2) {p2}")
|
||||
stars += 1
|
||||
except IOError:
|
||||
pass
|
||||
|
|
|
|||
43
2024-python/output/day_07.py
Normal file
43
2024-python/output/day_07.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
from collections import deque
|
||||
|
||||
from output import ints
|
||||
|
||||
|
||||
def solve(data):
|
||||
mul_add = calculate(data)
|
||||
mul_add_concat = calculate(data, concat=True)
|
||||
return mul_add, mul_add_concat
|
||||
|
||||
|
||||
def calculate(data, concat=False):
|
||||
values = list()
|
||||
for nums in [ints(line) for line in data.splitlines()]:
|
||||
T, start, *nums = nums
|
||||
E = len(nums)
|
||||
q = deque([(0, start)])
|
||||
ok = False
|
||||
while q:
|
||||
i, value = q.pop()
|
||||
if i == E:
|
||||
if value == T:
|
||||
ok = True
|
||||
continue
|
||||
if (a := value + nums[i]) <= T:
|
||||
q.append((i + 1, a))
|
||||
if (b := value * nums[i]) <= T:
|
||||
q.append((i + 1, b))
|
||||
if concat and (c := int(f"{value}{nums[i]}")) <= T:
|
||||
q.append((i + 1, c))
|
||||
if ok:
|
||||
values.append(T)
|
||||
return sum(values)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
with open("./input/07.txt", "r") as f:
|
||||
inp = f.read().strip()
|
||||
|
||||
p1, p2 = solve(inp)
|
||||
|
||||
print(p1)
|
||||
print(p2)
|
||||
Loading…
Add table
Reference in a new issue