-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
370 lines (309 loc) · 11.8 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import numpy as np
from typing import Tuple
import logging
logger = logging.basicConfig(level=logging.INFO)
# logger = logging.basicConfig(level=logging.DEBUG)
def get_sudoku_visualization_string(s, marked_cell=None):
string = ""
string += str("-" * 23)
string += "\n"
for row_idx, row in enumerate(s):
if row_idx % 3 == 0 and row_idx > 0:
string += "-" * 33
string += "\n"
for col_idx, val in enumerate(row):
if col_idx % 3 == 0 and col_idx > 0:
string += " | "
if (
marked_cell is not None
and row_idx == marked_cell[0]
and col_idx == marked_cell[1]
):
string += f"({val})" if val != 0 else " "
else:
string += f" {val} " if val != 0 else " "
string += "\n"
string += "-" * 33
return string
def check_if_number_in_array(number: int, array: np.ndarray):
return number in list(array.flatten())
s_start = np.array(
[
[3, 0, 0, 1, 0, 8, 0, 0, 7],
[7, 6, 0, 0, 9, 0, 0, 8, 4],
[0, 1, 0, 0, 0, 0, 0, 2, 0],
[0, 0, 0, 2, 8, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 5],
[0, 0, 0, 9, 5, 4, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 7, 0],
[5, 3, 0, 0, 4, 0, 0, 9, 1],
[9, 0, 0, 8, 0, 6, 0, 0, 2],
]
)
s_easy = np.array(
[
[0, 0, 0, 0, 5, 8, 4, 2, 7],
[0, 0, 8, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 7, 6, 0, 0],
[0, 5, 4, 2, 9, 0, 8, 7, 1],
[7, 6, 0, 0, 0, 0, 0, 4, 9],
[0, 1, 0, 0, 0, 0, 0, 5, 0],
[0, 2, 0, 3, 7, 0, 0, 9, 8],
[4, 0, 7, 8, 0, 5, 1, 0, 0],
[5, 8, 3, 0, 2, 0, 0, 6, 4],
]
)
s_hard = np.array(
[
[0, 2, 0, 0, 0, 0, 4, 0, 0],
[0, 6, 0, 2, 8, 0, 0, 5, 0],
[7, 0, 4, 0, 0, 0, 0, 1, 0],
[0, 4, 8, 0, 0, 2, 0, 3, 0],
[0, 0, 0, 0, 3, 0, 6, 0, 0],
[6, 0, 0, 0, 0, 9, 8, 0, 0],
[0, 0, 0, 0, 6, 0, 0, 0, 5],
[0, 0, 7, 0, 1, 5, 0, 0, 2],
[0, 0, 0, 0, 0, 8, 0, 0, 0],
]
)
s_expert = np.array(
[
[8, 0, 0, 0, 0, 2, 0, 0, 0],
[0, 0, 4, 0, 0, 0, 0, 9, 0],
[9, 0, 0, 0, 5, 6, 8, 0, 0],
[5, 0, 0, 2, 0, 0, 0, 0, 0],
[0, 0, 3, 0, 7, 5, 0, 0, 6],
[0, 0, 0, 4, 0, 0, 7, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 3],
[0, 0, 0, 7, 0, 0, 0, 0, 0],
[4, 0, 0, 0, 8, 9, 6, 0, 0],
]
)
# s_start = np.array(
# [
# [3, 0, 0, 1, 2, 8, 0, 0, 7],
# [7, 6, 2, 3, 9, 5, 0, 8, 4],
# [8, 1, 0, 4, 6, 7, 0, 2, 0],
# [0, 0, 0, 2, 8, 1, 0, 0, 0],
# [1, 0, 0, 6, 7, 3, 0, 4, 5],
# [2, 0, 0, 9, 5, 4, 0, 0, 0],
# [0, 2, 0, 5, 0, 9, 0, 7, 0],
# [5, 3, 0, 7, 4, 2, 0, 9, 1],
# [9, 0, 0, 8, 0, 6, 0, 0, 2],
# ]
# )
s = s_hard
logging.info(get_sudoku_visualization_string(s))
assert s.shape[0] == 9
assert s.shape[1] == 9
# create exclusion mask
mask_exclude = np.zeros((9, 9, 9))
def apply_rules(s_in):
sum_0 = 0
while sum_0 != np.sum(s_in) and is_valid(s_in):
sum_0 = np.sum(s_in)
mask_exclude = create_mask_exclude(s_in)
s_in = apply_exclusion_rule(s_in, mask_exclude)
mask_exclude = create_mask_exclude(s_in)
s_in = apply_combination_rules(s_in, mask_exclude)
logging.info(f"Stop applying rules, no improvement...")
return s_in
def create_mask_exclude(s_in):
for row_idx in range(9):
for col_idx in range(9):
if s_in[row_idx, col_idx] > 0:
# ALREADY DEFINED
number = s_in[row_idx, col_idx]
mask = np.ones(9)
mask[number - 1] = 0
mask_exclude[row_idx, col_idx, :] = mask
logging.debug(f"Cell {row_idx} {col_idx}: {number} is already defined.")
else:
for number in range(1, 10):
# ROW
row = s_in[row_idx]
bool_row = check_if_number_in_array(number, row)
mask_exclude[row_idx, col_idx, number - 1] = (
mask_exclude[row_idx, col_idx, number - 1] or bool_row
)
if bool_row:
logging.debug(
f"Cell {row_idx} {col_idx}: {number} is in row {row}"
)
# COLUMN
col = s_in[:, col_idx]
bool_col = check_if_number_in_array(number, col)
mask_exclude[row_idx, col_idx, number - 1] = (
mask_exclude[row_idx, col_idx, number - 1] or bool_col
)
if bool_col:
logging.debug(
f"Cell {row_idx} {col_idx}: {number} is in col {col}"
)
# 3x3 CELL
cell_start_row = (row_idx // 3) * 3
cell_start_col = (col_idx // 3) * 3
cell = s_in[
cell_start_row : cell_start_row + 3,
cell_start_col : cell_start_col + 3,
]
bool_cell = check_if_number_in_array(number, cell)
mask_exclude[row_idx, col_idx, number - 1] = (
mask_exclude[row_idx, col_idx, number - 1] or bool_cell
)
if bool_cell:
logging.debug(
f"Cell {row_idx} {col_idx}: {number} is in cell {cell.flatten()}"
)
return mask_exclude
def apply_combination_rules(s_in, mask_exclude):
mask_block = np.transpose(mask_exclude, (2, 0, 1))
for idx in range(9):
number = idx + 1
logging.debug(f"Check number: {number}")
# ROW
for row_idx in range(9):
row = np.logical_not(mask_block[idx, row_idx])
if np.sum(row) == 1 and number not in s_in[row_idx]:
col_idx = int(np.where(row)[0][0])
s_in[row_idx, col_idx] = number
logging.info(
f"Number {number} can only be in row {row_idx} in col {col_idx} because of row"
)
logging.info(get_sudoku_visualization_string(s_in, (row_idx, col_idx)))
return s_in
for col_idx in range(9):
col = np.logical_not(mask_block[idx, :, col_idx])
if np.sum(col) == 1 and number not in s_in[:, col_idx]:
row_idx = int(np.where(col)[0][0])
s_in[row_idx, col_idx] = number
logging.info(
f"Number {number} can only be in row {row_idx} in col {col_idx} because of col"
)
logging.info(get_sudoku_visualization_string(s_in, (row_idx, col_idx)))
return s_in
for cell_row_idx in range(3):
for cell_col_idx in range(3):
cell_row_start = cell_row_idx * 3
cell_col_start = cell_col_idx * 3
cell = np.logical_not(
mask_block[
idx,
cell_row_start : cell_row_start + 3,
cell_col_start : cell_col_start + 3,
]
)
cell_values = s_in[
cell_row_start : cell_row_start + 3,
cell_col_start : cell_col_start + 3,
]
if np.sum(cell.flatten()) == 1 and number not in cell_values:
idx_flat = int(np.where(cell.flatten())[0][0])
row_idx = idx_flat // 3
col_idx = idx_flat % 3
row_idx = cell_row_start + row_idx
col_idx = cell_col_start + col_idx
s_in[row_idx, col_idx] = number
logging.info(
f"Number {number} can only be in row {row_idx} col {col_idx} in cell {cell_row_idx}, {cell_col_idx}"
)
logging.info(
get_sudoku_visualization_string(s_in, (row_idx, col_idx))
)
return s_in
return s_in
def apply_exclusion_rule(s_in, mask_exclude):
# EXLUSION ALGOs (check if we can find cells where one single number is the only one that fits)
for row_idx in range(9):
for col_idx in range(9):
# INSERT Numbers that can be determined by exclusion
logging.debug(
f"Cell {row_idx} {col_idx} with {mask_exclude[row_idx, col_idx]}"
)
if s_in[row_idx, col_idx] > 0:
# jump over if values is existing
continue
if np.sum(np.logical_not(mask_exclude[row_idx, col_idx])) == 1:
new_val = (
np.where(np.logical_not(mask_exclude[row_idx, col_idx]))[0]
) + 1
s_in[row_idx, col_idx] = int(new_val[0])
logging.info(
f"Able to exclude all other number except {new_val} in {row_idx} {col_idx}"
)
logging.debug(
get_sudoku_visualization_string(
s_in, marked_cell=(row_idx, col_idx)
)
)
return s_in
def get_guess(mask_exclude):
# count nunmber of options
n_options = np.sum(mask_exclude == 0, axis=2)
# replace all items that are defined (value=1)
n_options = np.where(n_options == 1, np.nan, n_options)
# get minimum
idx_flat = np.nanargmin(n_options.flatten())
row_idx = idx_flat // 9
col_idx = idx_flat % 9
options = np.where(np.logical_not(mask_exclude[row_idx, col_idx]))[0] + 1
return dict(row_idx=row_idx, col_idx=col_idx, options=options)
def is_valid(s_in):
def has_duplicates(arr):
# drop zeros
arr = arr[arr != 0]
return len(arr) != len(set(arr))
# rows
for i in range(9):
if has_duplicates(s_in[i]):
print(f"invalid row {i}: {s_in[i]} ")
return False
if has_duplicates(s_in[:, i]):
print(f"invalid col {i}: {s_in[:,i]} ")
return False
for cell_row_idx in range(3):
for cell_col_idx in range(3):
cell_row_start = cell_row_idx * 3
cell_col_start = cell_col_idx * 3
cell_values = s_in[
cell_row_start : cell_row_start + 3, cell_col_start : cell_col_start + 3
]
if has_duplicates(cell_values.flatten()):
print(f"invalid cell {cell_row_idx},{cell_col_start}: {cell_values}")
return False
return True
guessing = False
s = apply_rules(s)
# ASSUMPTION / BACK TRACKING
def recursive_back_tracking(s_in):
mask_exclude = create_mask_exclude(s_in)
guess_dict = get_guess(mask_exclude)
options = guess_dict["options"]
row_idx = guess_dict["row_idx"]
col_idx = guess_dict["col_idx"]
guessing = True
for guess in options:
s_temp = s_in.copy()
s_temp[row_idx, col_idx] = guess
logging.info(f"Assume guess {guess} at row {row_idx} col {col_idx}")
logging.info(
get_sudoku_visualization_string(s_temp, marked_cell=(row_idx, col_idx))
)
s_temp = apply_rules(s_temp.copy())
if is_valid(s_temp):
logging.debug(
f"Guess {guess} at row {row_idx} col {col_idx} is not invalid"
)
if np.sum(s_temp == 0) > 0:
s_temp = recursive_back_tracking(s_temp)
else:
return s_temp
else:
logging.debug(f"Guess {guess} at row {row_idx} col {col_idx} is invalid")
return None
return None
if np.sum(s == 0) > 0:
s = recursive_back_tracking(s)
print()
print("\n--------- Final Result --------")
logging.info(get_sudoku_visualization_string(s))