Day 14
This commit is contained in:
34
day14/part2.py
Normal file
34
day14/part2.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import re
|
||||
|
||||
lines = (x.strip() for x in open("input.txt"))
|
||||
mem = {}
|
||||
regex_mask = re.compile(r"mask = (.+)")
|
||||
regex_mem = re.compile(r"mem\[(.*)] = (.+)")
|
||||
mask = ""
|
||||
|
||||
|
||||
def combination(res, sum=0):
|
||||
if len(res) == 0:
|
||||
yield sum
|
||||
else:
|
||||
head, tail = res[0], res[1:]
|
||||
if head != 'X':
|
||||
yield from combination(tail, sum=sum*2+int(head))
|
||||
else:
|
||||
yield from combination(tail, sum=sum*2)
|
||||
yield from combination(tail, sum=sum*2+1)
|
||||
|
||||
|
||||
for line in lines:
|
||||
match = regex_mask.match(line)
|
||||
if match is not None:
|
||||
mask = match.group(1)
|
||||
else:
|
||||
match = regex_mem.match(line)
|
||||
addr, dec = list(map(int, match.groups()))
|
||||
bin = format(addr, '036b')
|
||||
res = "".join((a if b == '0' else b) for a, b in zip(bin, mask))
|
||||
for x in combination(res):
|
||||
mem[x] = dec
|
||||
|
||||
print(sum(map(lambda x: mem[x], mem)))
|
||||
Reference in New Issue
Block a user