35 lines
884 B
Python
35 lines
884 B
Python
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 = [(a if b == '0' else b) for a, b in zip(bin, mask)]
|
|
for x in combination(res):
|
|
mem[x] = dec
|
|
|
|
print(sum(mem.values()))
|