-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.py
36 lines (26 loc) · 899 Bytes
/
day14.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
import re
MEMORY_REGEX = re.compile("^mem\\[([0-9]+)\\] = ([0-9]+)$")
input_filename = __file__.split(".")[0] + ".input"
with open(input_filename) as f:
raw = f.read().strip().split("\n")
def _apply_mask(mask, value):
value = bin(int(value)).replace("b", "")
longest = len(mask) # Assume mask is always longest
value = value.zfill(longest) # fill with leading zeros
result = ""
for cm, cv in zip(mask, value):
if cm in ('1', '0'):
result += cm
else:
result += cv
return int(result, 2)
memory = {}
current_bitmask = None
for line in raw:
if line.startswith("mask"):
_, current_bitmask = line.split(" = ")
else:
address, value = re.match(MEMORY_REGEX, line).groups()
adjusted_value = _apply_mask(current_bitmask, value)
memory[address] = adjusted_value
print(sum(memory.values()))