aboutsummaryrefslogtreecommitdiff
path: root/2023/15
diff options
context:
space:
mode:
authorMarvin Borner2023-12-15 12:03:52 +0100
committerMarvin Borner2023-12-15 12:03:52 +0100
commit8a65d55c981c79b16bf303b1b05245b4f889e43b (patch)
treee9db782ee8cd6e3861a63bae58245ed7461d988a /2023/15
parent9c60589f7a051664f211727d9d28068210fe813a (diff)
WHY PYTHON [[]]*256
Diffstat (limited to '2023/15')
-rw-r--r--2023/15/solve.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/2023/15/solve.py b/2023/15/solve.py
new file mode 100644
index 0000000..00d86d9
--- /dev/null
+++ b/2023/15/solve.py
@@ -0,0 +1,53 @@
+L = open("input").read().strip().split(",")
+
+
+def hash(s):
+ current = 0
+ for c in s:
+ current += ord(c)
+ current *= 17
+ current %= 256
+ return current
+
+
+def solve1():
+ res = 0
+ for l in L:
+ res += hash(l)
+ print(res)
+
+
+def solve2():
+ res = 0
+
+ boxes = dict() # defaultdict would be cheating!!1!!!1!
+ for l in L:
+ if l[-1] == "-":
+ label = l[:-1]
+ box = hash(label)
+ boxes[box] = [
+ (lab, foc) for (lab, foc) in boxes.get(box, []) if lab != label
+ ]
+ elif l[-2] == "=":
+ label = l[:-2]
+ focal = int(l[-1])
+ box = hash(label)
+ labels = [lab for (lab, foc) in boxes.get(box, [])]
+ if label in labels:
+ boxes[box] = [
+ (lab, focal if label == lab else foc)
+ for (lab, foc) in boxes[box]
+ ]
+ else:
+ if box not in boxes:
+ boxes[box] = []
+ boxes[box].append((label, focal))
+
+ for i, stacked in boxes.items():
+ for j, box in enumerate(stacked):
+ res += (i + 1) * (j + 1) * box[1]
+ print(res)
+
+
+solve1()
+solve2()