Day 15
This commit is contained in:
1 parent
f63d67f005
commit
5f260fcfe2
4 files changed
+214
No files matched your search
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys, re
|
||||
|
||||
|
||||
def HASH(string):
|
||||
res = 0
|
||||
for a in string:
|
||||
res += ord(a)
|
||||
res = res * 17 % 256
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
instr = open(sys.argv[1]).read().strip('\n').split(',')
|
||||
|
||||
# challenge 1
|
||||
res1 = sum([HASH(a) for a in instr])
|
||||
|
||||
boxes = {}
|
||||
for i in instr:
|
||||
label, op, focus = re.findall(r'(\w+)(\-|\=)(\d*)', i)[0]
|
||||
box = HASH(label)
|
||||
if not box in boxes.keys(): boxes[box] = []
|
||||
present = boxes[box]
|
||||
if op == '=':
|
||||
for i, lens in enumerate(present):
|
||||
if lens[0] == label: present[i] = (label, int(focus))
|
||||
if not (label, int(focus)) in present: present.append((label, int(focus)))
|
||||
elif op == '-':
|
||||
for i, lens in enumerate(present):
|
||||
if lens[0] == label:
|
||||
present.remove(lens)
|
||||
break
|
||||
|
||||
res2 = 0
|
||||
for b, lenses in boxes.items():
|
||||
for i,l in enumerate(lenses):
|
||||
res2 += (b+1) * (i+1) * l[1]
|
||||
|
||||
res1 = str(res1)
|
||||
print(f"challenge 1:\n{res1}\n")
|
||||
|
||||
# challenge 2
|
||||
res2 = str(res2)
|
||||
print(f"challenge 2:\n{res2}\n")
|
||||
|
||||
Reference in new issue
Block a user