-
Notifications
You must be signed in to change notification settings - Fork 0
/
codeAdvent_14.py
157 lines (87 loc) · 2.49 KB
/
codeAdvent_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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
'''
Created on 13 August 2021
@author: Antonio Martínez Fernández
'''
ans = 0
mask = "000000000000000000000000000000000000"
dic = {}
def processMask(linea):
global mask
linea = linea.split("=")[1]
linea = linea.strip()
mask = linea
def processMem(linea):
global mask
aux = mask
i_substring = 0
linea = linea.strip()
num = int(linea.split("=")[1])
num = str(bin(num)[2:]) # -> binario
pos = linea.split("=")[0].split("[")[1]
pos = int(pos.replace("]", ""))
# aplicar filtro
for i in range(0, 36, 1):
if((len(mask)-i) <= len(num)):
if mask[i] == "X":
aux = aux[:i]+num[i_substring]+aux[i+1:]
i_substring += 1
aux = aux.replace("X", "0")
dic[pos] = aux
def processLine(linea):
if linea[1] == 'a':
processMask(linea)
else:
processMem(linea)
def processMem_v2(linea):
global mask
linea = linea.strip()
num = int(linea.split("=")[1]) # = numero
pos = linea.split("=")[0].split("[")[1]
pos = int(pos.replace("]", "")) # [memoria]
binary_pos = str(bin(pos)[2:]).rjust(36, '0') # ajustamos a 36 bits
aux = []
rec(mask, binary_pos, 0, aux)
for i in aux:
dic[int(i)] = num
def processLine_v2(linea):
if linea[1] == 'a':
processMask(linea)
else:
processMem_v2(linea)
def mainFunction():
global ans
archivo = open("input13.txt")
linea = archivo.readline()
while linea:
processLine(linea)
linea = archivo.readline()
for i in dic:
ans += int(int(dic.get(i), 2))
print("part 1 ", ans)
def mainFunction_v2():
global ans
global dic
dic = {}
ans = 0
archivo = open("input13.txt")
#
linea = archivo.readline()
while linea:
processLine_v2(linea)
linea = archivo.readline()
for i in dic:
ans += int(dic.get(i))
print("part 2 ", ans)
def rec(mask, mem, i, aux):
if i == 36:
aux.append(mem)
elif mask[i] == "X":
rec(mask, mem[:i]+"1"+mem[i+1:], i+1, aux)
rec(mask, mem[:i]+"0"+mem[i+1:], i+1, aux)
elif mask[i] == "1":
rec(mask, mem[:i]+"1"+mem[i+1:], i+1, aux)
else:
rec(mask, mem, i+1, aux)
if __name__ == '__main__':
mainFunction()
mainFunction_v2()