aboutsummaryrefslogtreecommitdiff
path: root/2020/14/puzzle-1.py
blob: 02e5d385013d4b4afee38fc8911b1ab6c0ecf85b (plain) (blame)
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
#!/usr/bin/env python3


def bitmask(mask: str, num: int) -> int:
	binary = bin(num)[2:]
	binary = "0" * (36 - len(binary)) + binary
	res = ""

	for i in range(len(binary)):
		if binary[i] == "1" and mask[i] == "0":
			res += "0"
		elif binary[i] == "0" and mask[i] == "1":
			res += "1"
		else:
			res += binary[i]

	return int(res, 2)


def main() -> None:
	with open("input", "r", encoding="utf-8") as f:
		lines = f.readlines()

	mem: dict[str, int] = {}
	mask = ""
	for line in lines:
		match line.split(" "):
			case ["mask", _, mask]:
				mask = mask
			case [addr, _, val]:
				mem[addr[4:-1]] = bitmask(mask, int(val))

	print(sum(mem.values()))


if __name__ == "__main__":
	main()