-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
238 lines (185 loc) · 7.27 KB
/
solver.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# -*- coding: utf-8 -*-
import sys, numpy as np
import itertools, copy
import cProfile
debug=0
C = np.arange(9)
class Sudogame(object):
def __init__(self, i):
"""
i è l'input
"""
self.rawinput = i
i = i.replace(' ','0')
i = i.replace('.','0')
self.game = (np.fromstring(i, dtype=np.uint8)-48).reshape(9,9)
self.candidates = [[ [] for x in C] for x in C]
self.supposition = None
def solve(self):
while np.any(self.game==0):
self.placed = False
if debug:
print 'New turn around'
for x,y,v in self.walk():
if not v:
candidates = self.get_candidates(x,y)
if debug:
print '--',x,y,'candidati:', candidates
if len(candidates) == 1:
self.found(x,y,candidates[0])
if not self.placed:
# colonne
for y in C:
prob_candidates = [np.array(self.candidates[ix][iy], 'i') for ix,iy in self.walkx(0,y) ]
candidates = np.concatenate( prob_candidates )
for p in np.arange(1,10):
if p in candidates:
if len( np.where( candidates == p )[0] ) == 1:
for x in C:
if p in prob_candidates[x]:
self.found(x,y,p)
# righe
for x in C:
prob_candidates = [np.array(self.candidates[ix][iy], 'i') for ix,iy in self.walky(x,0) ]
candidates = np.concatenate( prob_candidates )
for p in np.arange(1,10):
if p in candidates:
if len( np.where( candidates == p )[0] ) == 1:
for y in C:
if p in prob_candidates[y]:
self.found(x,y,p)
# box
for x,y in ((1,1), (1,4), (1,7),
(4,1), (4,4), (4,7),
(7,1), (7,4), (7,7)):
prob_candidates = [np.array(self.candidates[ix][iy], 'i') for ix,iy in self.walkbox(x,y) ]
candidates = np.concatenate( prob_candidates )
for p in np.arange(1,10):
if p in candidates:
if len( np.where( candidates == p )[0] ) == 1:
for n, (ix,iy) in enumerate(self.walkbox(x,y)):
if p in prob_candidates[n]:
self.found(ix,iy,p)
if not self.placed:
if self.supposition is None:
all_suppositions = []
for _,x,y in sorted(
[(len(self.candidates[x][y]), x,y) for x in C for y in C if len(self.candidates[x][y])>0]
):
for v in self.candidates[x][y]:
all_suppositions.append((x,y,v))
n_ipo = 0
# ipotesi!
(x,y,v) = all_suppositions[n_ipo]
self.supposition = {'game':self.game.copy(),
'cand':self.candidates[:],
'all_suppositions':all_suppositions,
'n_ipo':n_ipo}
if debug:
print 'ipotesi',x,y,v
self.found(x,y,v)
else:
#import ipdb; ipdb.set_trace()
# Non trovato, ipotesi inutile
S = self.supposition
self.game = S['game']
self.candidates = S['cand']
S['n_ipo'] += 1
(x,y,v) = S['all_suppositions'][S['n_ipo']]
if debug:
print 'ipotesi',x,y,v
#try:
self.found(x,y,v)
#except:
# import ipdb; ipdb.set_trace()
continue
if not self.placed:
print 'FALLITO'
#print self.asstring()
import ipdb;ipdb.set_trace()
#raise ValueError
break
return
def asstring(self):
return ''.join(map(str,self.game.flatten())).replace('0','.')
def pprint(self):
for y in C:
print self.game[:,y]
def walk(self):
#return [(x,y,self.game[x,y]) for _,x,y in sorted([(len(self.candidates[x][y]), x,y) for x in C for y in C])]
for x in C:
for y in C:
yield x,y, self.game[x,y]
def walkx(self,_,y):
"""return all coordinates of the row"""
for x in C:
yield x,y
def takex(self,_,y):
"""return all values of the column"""
return self.game[0:9,y]
def walky(self,x,_):
for y in C:
yield x,y
def takey(self,x,_):
"""return all values of the row"""
return self.game[x,0:9]
def walkbox(self,x,y):
x = (x/3)*3
y = (y/3)*3
for cx in range(x, x+3):
for cy in range(y, y+3):
yield cx,cy
def takebox(self,x,y):
"""return all values of the box"""
x = (x/3)*3
y = (y/3)*3
return self.game[ x:x+3, y:y+3 ].flatten()
def row(self,x):
q =self.game[x,:]
return q[q>0]
def col(self,y):
q=self.game[:,y]
return q[q>0]
def box(self,x,y):
x = (x/3)*3
y = (y/3)*3
q=self.game[x:x+3,y:y+3]
return q[q>0]
def get_candidates(self, x,y):
if not len(self.candidates[x][y]):
self.candidates[x][y] = \
np.setdiff1d(
np.arange(1,10),
np.unique(
np.concatenate( ( self.takex(x,y),
self.takey(x,y),
self.takebox(x,y))
) )
).tolist()
return self.candidates[x][y]
def found(self,x,y,v):
self.game[x,y] = v
self.placed = True
self.candidates[x][y] = []
for c in C:
if v in self.candidates[c][y]:
self.candidates[c][y].remove(v)
if v in self.candidates[x][c]:
self.candidates[x][c].remove(v)
bx = (x/3)*3
by = (y/3)*3
for cx in range(bx, bx+3):
for cy in range(by, by+3):
if v in self.candidates[cx][cy]:
self.candidates[cx][cy].remove(v)
if debug:
print '--',x,y,'found:', v
if __name__ == '__main__':
for line in file('collection.txt').xreadlines():
line = line.strip()
print line,
s = Sudogame(line)
s.solve()
#cProfile.run('s.solve()', 'profile.testing')
print s.asstring()
#break