From a90269f7f9e1d223d27311c3c7a8c83f0e61a0f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Fri, 15 Dec 2023 10:01:49 +0100 Subject: [PATCH] Solve 2023:15 "Lens Library" WALLOFTEXT for part 2, took me 90 minutes to find this important text: > Each step begins with a sequence of letters that > indicate the label of the lens on which the step > operates. The result of running the HASH algorithm > on the label indicates the correct box for that > step. It also clarifies how part 2 and part 1 relates. --- 2023-python/output/day_15.py | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2023-python/output/day_15.py diff --git a/2023-python/output/day_15.py b/2023-python/output/day_15.py new file mode 100644 index 0000000..31a3e98 --- /dev/null +++ b/2023-python/output/day_15.py @@ -0,0 +1,63 @@ +from collections import OrderedDict, defaultdict + +from output import answer + +n = 15 +title = "Lens Library" + + +@answer(1, "Sum of HASH algorithm results: {}") +def part_1(presolved): + return presolved[0] + + +@answer(2, "Focusing power of the resulting configuration: {}") +def part_2(presolved): + return presolved[1] + + +def presolve(data): + def h(s): + v = 0 + for a in s: + if a == "\n": + continue + v += ord(a) + v *= 17 + v = v % 256 + return v + + p1 = sum(h(c) for c in data.split(",")) + + b = defaultdict(OrderedDict) + for lr in data.split(","): + if "=" in lr: + l, r = lr.split("=") + if r == "": + continue + k = h(l) + b[k][l] = r + if "-" in lr: + l, _r = lr.split("-") + k = h(l) + if l in b[k]: + del b[k][l] + p2 = 0 + for i, c in b.items(): + for j, f in enumerate(b[i].values(), 1): + p2 += (i + 1) * j * int(f) + + return p1, p2 + + +if __name__ == "__main__": + with open("./input/16.txt", "r") as f: + inp = f.read().strip() + + inp = presolve(inp) + + a = part_1(inp) + b = part_2(inp) + + assert a == 509784 + assert b == 230197