-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.2.py
45 lines (40 loc) · 1.2 KB
/
14.2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
with open('input/14.txt') as f:
content = [x.strip() for x in f.readlines()]
operations = [x.split(' = ') for x in content]
def get_all_addresses(address):
# start most significant
i = address.find('X')
if i == -1:
# all done
return [address]
# set the bit both ways and get the addresses from the next floating bit
return get_all_addresses(address[:i] + '0' + address[i+1:]) \
+ get_all_addresses(address[:i] + '1' + address[i+1:])
mem = {}
mask = 0
for op in operations:
print(op)
if op[0] == 'mask':
# always 36 bits
mask = op[1][::-1]
mask = mask + '0'*(36-len(mask))
mask = mask[::-1]
elif 'mem' in op[0]:
loc = str(bin(int(op[0][4:-1]))[2:])[::-1]
loc = loc + '0'*(36-len(loc))
loc = loc[::-1]
value = str(bin(int(op[1])))[2:][::-1]
value = value + '0'*(36-len(value))
value = int(value[::-1], 2)
# print(mask[::-1], value)
address_mask = []
i = 0
for x in mask[::-1]:
if x == '0':
address_mask.append(loc[::-1][i])
else:
address_mask.append(x)
i += 1
for mem_loc in get_all_addresses(''.join(address_mask[::-1])):
mem[mem_loc] = value
print('Part Two:', sum(mem.values()))