-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.py
60 lines (54 loc) · 1.43 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from downloadInput import start
from parse import parse
day = 14
input=[]
file = "day%d/input.txt" % day
# file = "test.txt"
def part1(input):
def masked(mask, val):
val = list(format(val, "036b"))
for i in range(len(mask)):
if mask[i] != 'X':
val[i] = mask[i]
return int("".join(val),2)
memory = dict()
mask = ""
for line in open(file, "r").readlines():
if line[1] == "a":
mask = parse("mask = {}", line)[0]
while line[1] == "e":
mem, val = parse("mem[{:d}] = {:d}", line)
memory[mem] = masked(mask, val)
break
return sum(memory.values())
def part2(input):
def masked(mask, val):
val = list(format(val, "036b"))
pos = []
for i in range(len(mask)):
if mask[i] == "1":
val[i]= mask[i]
elif mask[i] == "X":
pos.append(i)
rez = []
for i in range(2**len(pos)):
target = list(format(i, "0%db"%len(pos)))
for x,y in zip(pos,target):
val[x] = y
rez.append(int("".join(val),2))
return rez
memory = dict()
mask = ""
for line in open(file, "r").readlines():
if line[1] == "a":
mask = parse("mask = {}", line)[0]
while line[1] == "e":
mem, val = parse("mem[{:d}] = {:d}", line)
for x in masked(mask, mem):
memory[x] = val
break
return sum(memory.values())
def day14(input):
print("Day 14 part1: ", part1(input))
print("Day 14 part2: ", part2(input))
day14(input)