-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2_bitops.py
51 lines (37 loc) · 1.2 KB
/
part2_bitops.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
46
47
48
49
50
51
import itertools
_TESTCASE = """\
mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1
""".strip().splitlines()
def compute(data):
"""
>>> compute(_TESTCASE)
208
"""
mem = {}
mask = None
instructions = map(lambda s: s.split(" = "), data)
for var, val in instructions:
if var == "mask":
mask = val
elif var.startswith("mem"):
_, _, addr = var.rstrip("]").partition("[")
mask_passthrough = int(mask.replace("X", "1"), 2)
addr = int(addr) | mask_passthrough
# noinspection PyTypeChecker
for comb in map(iter, itertools.product("01", repeat=mask.count("X"))):
mask_overwrite = int(
"".join(next(comb) if bit == "X" else bit for bit in mask.replace("0", "1")),
2,
)
mem[addr & mask_overwrite] = int(val)
return sum(mem.values())
def main():
import pathlib
input_path = pathlib.Path(__file__).with_name("input.txt")
with input_path.open() as f:
print(compute(f.read().strip().splitlines()))
if __name__ == "__main__":
main()