-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.py
40 lines (37 loc) · 1.33 KB
/
14.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
# Problem: https://adventofcode.com/2020/day/14
# Input
from sys import stdin
program = list(stdin)
# Part 1
from collections import defaultdict
mem = defaultdict(int)
for line in program:
if line.startswith("mask = "):
mask = line.strip()[-36:]
ones_mask = int(mask.replace("X", "0"), base=2)
zeroes_mask = int(mask.replace("X", "1"), base=2)
else:
address, value = line[4:].split("] = ")
# override ones using OR, and override zeroes using AND
mem[int(address)] = (int(value) | ones_mask) & zeroes_mask
print(sum(mem.values()))
# Part 2
from itertools import product
mem = defaultdict(int)
for line in program:
if line.startswith("mask = "):
mask = line.strip()[-36:]
ones_mask = int(mask.replace("X", "0"), base=2)
floating_mask = int(mask.replace("0", "1").replace("X", "0"), base=2)
floating_values = [
(0, 1 << position)
for position, char in enumerate(reversed(mask))
if char == "X"
]
else:
address, value = line[4:].split("] = ")
# override ones, and override floating bits to zeroes
base_address = (int(address) | ones_mask) & floating_mask
for floating_value in product(*floating_values):
mem[base_address + sum(floating_value)] = int(value)
print(sum(mem.values()))