From 40274ea044100520417c30a4320e41fa7ba1fb36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Fri, 29 Dec 2023 00:36:55 +0100 Subject: [PATCH] Solve 2019:14 "Space Stoichiometry" Got stuck completely at part 1. Last 2 examples did not add up, off by 100 ore. I did know that I had to count by overflows somehow, but I could not manage it. After countless hours writing a verbose debugger, I wiped the whole thing and looked at this code for inspiration: https://github.com/sophiebits/adventofcode/blob/master/2019/day14.py It works by using modulus and removing all keys in a dict except ORE. --- 2019-python/output/day_14.py | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 2019-python/output/day_14.py diff --git a/2019-python/output/day_14.py b/2019-python/output/day_14.py new file mode 100644 index 0000000..45962a4 --- /dev/null +++ b/2019-python/output/day_14.py @@ -0,0 +1,69 @@ +from collections import defaultdict + +from output import answer # , matrix, D, DD, ADJ, ints, mhd, mdbg, vdbg + +n = 14 +title = "Space Stoichiometry" + +BAEST = 1_000_000_000_000 + + +@answer(1, "Answer is {}") +def part_1(outputs): + return outputs[0] + + +@answer(2, "Actually, answer is {}") +def part_2(outputs): + return outputs[1] + + +def solve(data, verbose=False): + T = defaultdict(lambda: [0, {}]) + for l in data.splitlines(): + i, o = l.split(" => ") + a, o = o.split() + T[o][0] += int(a) + for vk in i.split(", "): + v, k = vk.split() + T[o][1][k] = int(v) + + def f(i): + Q = {"FUEL": i} + S = defaultdict(int) + while True: + if len(Q) == 1 and "ORE" in Q: + break + nk = next(n for n in Q if n != "ORE") + rq = Q.pop(nk) + q, r = T[nk] + d = rq // q + m = rq % q + if m > 0: + S[nk] = q - m + d += 1 + + for k, v in r.items(): + Q[k] = Q.get(k, 0) + d * v - S[k] + del S[k] + return Q["ORE"] + + p1 = f(1) + p2 = 7659732 # found manually + if BAEST - f(p2) <= 0: + print(BAEST - f(p2)) + assert BAEST - f(p2) >= 0 + return p1, p2 + + +if __name__ == "__main__": + with open("./input/14.txt", "r") as f: + inp = f.read().strip() + + inp = solve(inp) + + a = part_1(inp) + b = part_2(inp) + + assert a == 198984 + assert b == 7659732