-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
69 lines (54 loc) · 2.09 KB
/
main.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from src.common.file_utils import get_path, read_lines
import re
BITS = 36
def part_one(filename: str) -> int:
lines = read_lines(get_path(__file__, filename))
memory = {}
for line in lines:
splitted = line.split("=")
key, val = splitted[0].strip(), splitted[1].strip()
if key == "mask":
mask = val
else:
address = int(re.search(r'mem\[(\d+)]', key).groups()[0])
val = list('{:036b}'.format(int(val)))
for idx, c in enumerate(mask):
val[idx] = c if c != "X" else val[idx]
memory[address] = int("".join(val), 2)
return sum(memory.values())
def part_two(filename: str) -> int:
lines = read_lines(get_path(__file__, filename))
memory = {}
for line in lines:
splitted = line.split("=")
key, val = splitted[0].strip(), splitted[1].strip()
if key == "mask":
mask = val
else:
address = int(re.search(r'mem\[(\d+)]', key).groups()[0])
address_base = list('{:036b}'.format(address))
floating = 0
# replace with 1's, mark x's with {} for formatting
for i in range(BITS):
if mask[i] == "X":
address_base[i] = "{}"
floating += 1
elif mask[i] == "1":
address_base[i] = "1"
format_address = "".join(address_base)
if floating > 0:
bin_format = "0{}b".format(floating)
# insert each binary number up to 2**floating into positions of X's
for i in range(2 ** floating):
mem_address = format_address.format(*format(i, bin_format))
memory[int(mem_address, 2)] = int(val)
else:
memory[int("".join(format_address), 2)] = int(val)
return sum(memory.values())
if __name__ == '__main__':
print("---Part One---")
part_one_res = part_one("input.txt")
print(part_one_res)
print("---Part Two---")
part_two_res = part_two("input.txt")
print(part_two_res)