1
+ import os
2
+ import sys
3
+ import itertools
4
+
5
+ debug = False
6
+ fileName = ""
7
+ try :
8
+ fileName = sys .argv [1 ]
9
+ if len (fileName ) < 1 :
10
+ fileName = "14.txt"
11
+ except :
12
+ fileName = "14.txt"
13
+ print (fileName )
14
+
15
+ memory = {}
16
+ #for i in range(2 ** 36):
17
+ # memory.append(0)
18
+
19
+ with open (fileName ) as file :
20
+ commands = file .readlines ()
21
+
22
+ mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
23
+ for command in commands :
24
+ if command [0 :4 ] == "mask" :
25
+ mask = command [7 :43 ]
26
+ else :
27
+ if len (mask ) != 36 :
28
+ print ("!!!!!Bad mask!!!!!" )
29
+
30
+ index = command [4 :command .find ("]" )]
31
+ inValue = command [command .find ("=" ) + 2 :]
32
+ value = bin (int (inValue )).replace ("0b" ,"" )
33
+
34
+ if len (value ) < 36 :
35
+ numAppend = 36 - len (value )
36
+ append = ""
37
+ for i in range (numAppend ):
38
+ append = append + "0"
39
+ value = append + value
40
+
41
+ #compute real value
42
+ real = ""
43
+ for i in range (36 ):
44
+ if mask [i ] == "1" or mask [i ] == "0" :
45
+ real = real + mask [i ]
46
+ else :
47
+ real = real + value [i ]
48
+ intVal = int (real , 2 )
49
+ memory [index ] = intVal
50
+
51
+ #get sum of memory
52
+ total = 0
53
+ for item in memory :
54
+ total += memory [item ]
55
+ print (total )
56
+
57
+ #part 2
58
+ memory = {}
59
+ mask = "000000000000000000000000000000000000"
60
+ for command in commands :
61
+ if command [0 :4 ] == "mask" :
62
+ mask = command [7 :43 ]
63
+ #print("msk",mask)
64
+ else :
65
+ if len (mask ) != 36 :
66
+ print ("!!!!!Bad mask!!!!!" )
67
+
68
+ index = bin (int (command [4 :command .find ("]" )])).replace ("0b" ,"" )
69
+ value = int (command [command .find ("=" ) + 2 :])
70
+
71
+ if len (index ) < 36 :
72
+ numAppend = 36 - len (index )
73
+ append = ""
74
+ for i in range (numAppend ):
75
+ append = append + "0"
76
+ index = append + index
77
+ #print("pre", index, int(index, 2))
78
+ addresses = []
79
+ newIndex = ""
80
+ for i in range (36 ):
81
+ if mask [i ] == "1" or mask [i ] == "X" :
82
+ newIndex = newIndex + mask [i ]
83
+ else :
84
+ newIndex = newIndex + index [i ]
85
+ index = newIndex
86
+
87
+ floating = mask .count ("X" )
88
+ perms = itertools .product ([0 , 1 ], repeat = floating )
89
+ #print("pst",index)
90
+ for perm in list (perms ):
91
+ addr = index
92
+ for i in range (floating ):
93
+ addr = addr .replace ("X" ,str (perm [i ]),1 )
94
+ #print("itr",addr,int(addr,2),"*")
95
+ addresses .append (int (addr ,2 ))
96
+ if floating == 0 :
97
+ #print(index, int(index,2), "~")
98
+ addresses .append (int (index ,2 ))
99
+
100
+ #print(addresses)
101
+ for address in addresses :
102
+ memory [address ] = value
103
+
104
+ #get sum of memory
105
+ #print(memory)
106
+ total = 0
107
+ for item in memory :
108
+ total += memory [item ]
109
+ print (total )
0 commit comments