-
Notifications
You must be signed in to change notification settings - Fork 1
/
sudokuLib.py
239 lines (171 loc) · 5.81 KB
/
sudokuLib.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
239
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 22 21:24:36 2014
@author: Ricardo Guerrero Gómez-Olmedo
"""
import os
import numpy as np
from matplotlib.mlab import find
from sys import platform
def sudokuPrinter(matrix):
'''
sudokuPrinter takes a sudoku contained in a numpy array and prints it
in a friendly way.
Parameters
----------
matrix: array_like
It contains the sudoku matrix.
'''
rows, columns = matrix.shape
line = ' ' + '+'.join(['-'*3]*3)
for a in range(0,rows):
if a and a%3 == 0:
print line
str_row = ''.join(str(val) for val in matrix[a,:])
print ' ' + '|'.join(str_row[i:i+3] for i in range(0,len(str_row),3)),
print '\n',
print '\n'
def mySquare(matrix, a, b):
'''
This function returns the square to which the variable in coordinates
a,b belongs.
Parameters
----------
matrix: array_like
It contains the sudoku matrix.
a : int
Current row.
b : int
Current column.
Returns
-------
squares : array_like
Returns a sub array from `squares` that contains the 3x3 square
to which belongs the element located in `matrix`[`a`,`b`]
'''
#Converting full grid to collection of 3x3 squares
squares = np.swapaxes(matrix.reshape(3,3,3,-1),1,2)
#mapping indexes a,b in matrix to c,d in squares
equiv = {0: [0,1,2], 1: [3,4,5], 2: [6,7,8]}
c = [key for key in equiv if a in equiv[key]][0]
d = [key for key in equiv if b in equiv[key]][0]
return squares[c,d]
solution = None
def sudokuSolver(matrix):
'''
This sudoku solver algorithm is based on the recursive backtracking
algorithm described in [1].
[1] http://es.wikipedia.org/wiki/Sudoku_backtracking
Parameters
----------
matrix: array_like
It contains the sudoku matrix.
'''
matbool = matrix != 0
solverRec(0,0, matrix, matbool)
return solution
def solverRec(i,j, matrix, matbool):
'''
This is a helper recursive function used by sudokuSolver.
Parameters
----------
i : int
Current row.
j : int
Current column.
matrix: array_like
It contains the sudoku matrix.
matbool: array_like
It reflects the initial state. True indicates initial values that
must not be changed. False indicates that the value could be changed.
'''
global solution
if matbool[i,j] == False:
for k in range(1,10):
matrix[i,j] = k
#checking if value is plausible in row, col and square
if len(find(matrix[i,:] == k)) == 1 and \
len(find(matrix[:,j] == k)) == 1 and \
len(find(mySquare(matrix,i,j) == k)) == 1:
if i == 8 and j == 8:
solution = matrix.copy()
elif i < 8 and j == 8:
solverRec(i+1, 0, matrix, matbool)
else:
solverRec(i, j+1, matrix, matbool)
matrix[i,j] = 0
else:
if i == 8 and j == 8:
solution = matrix.copy()
elif i < 8 and j == 8:
solverRec(i+1, 0, matrix, matbool)
else:
solverRec(i, j+1, matrix, matbool)
def sudokuChecker(matrix):
'''
sudokuChecker takes a 9x9 sudoku and return True if it is a valid sudoku,
i.e. it meets all the rules.
Parameters
----------
matrix: array_like
`matrix` is a numpy.array that contains a 9x9 sudoku.
Returns
-------
valid : bool
If any of the numbers in `matrix` does not follow the 3 sudoku's rules,
`out` will be False. Otherwise will be True.
'''
valid = True
if len( np.hstack((find(matrix <1), find(matrix > 9))) ) != 0:
valid = False
return valid
for i in range(0,9):
for j in range(0,9):
k = matrix[i,j]
if len(find(matrix[i,:] == k)) > 1 or \
len(find(matrix[:,j] == k)) > 1 or \
len(find(mySquare(matrix,i,j) == k)) > 1:
valid = False
return valid
def sudokuInputChecker(matrix):
'''
inputChecker takes a sudoku and return True if it is a valid initial
sudoku, i.e. it's shape is 9x9 and it meets all the rules for non-zero values.
Parameters
----------
matrix: array_like
`matrix` is a numpy.array that contains a 9x9 sudoku.
Returns
-------
valid : bool
If the input matrix is correct, a True value will be returned.
'''
valid = True
if matrix.shape != (9,9) or\
matrix.min() < 0 or \
matrix.max() > 9:
valid = False
return valid
for i in range(0,9):
for j in range(0,9):
k = matrix[i,j]
if k != 0:
if len(find(matrix[i,:] == k)) > 1 or \
len(find(matrix[:,j] == k)) > 1 or \
len(find(mySquare(matrix,i,j) == k)) > 1:
valid = False
return valid
def pause():
'''
This function pause the execution until the user press any key to continue
\n(in Windows) or press Enter (in Linux)
'''
if platform == 'win32':
os.system('pause')
elif platform == 'linux' or platform == 'linux2':
print('Press Enter to continue ...'),
try:
raw_input()
except:
pass
print('\n')