From 81fe14a407478bb640c2c6f99862b75c2a911fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Sat, 7 Dec 2024 21:15:19 +0100 Subject: [PATCH] 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. --- 2024-python/aoc.py | 4 ++-- 2024-python/output/day_07.py | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 2024-python/output/day_07.py diff --git a/2024-python/aoc.py b/2024-python/aoc.py index 8adeee7..1842c0a 100644 --- a/2024-python/aoc.py +++ b/2024-python/aoc.py @@ -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 diff --git a/2024-python/output/day_07.py b/2024-python/output/day_07.py new file mode 100644 index 0000000..87c0ee1 --- /dev/null +++ b/2024-python/output/day_07.py @@ -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)