-
Notifications
You must be signed in to change notification settings - Fork 1
/
sudoku_solver.py
133 lines (105 loc) · 3.01 KB
/
sudoku_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
#!/usr/bin/python
from z3 import *
import argparse
import itertools
import time
problem1 = [
[ 9, 0, 0, 0, 1, 0, 5, 0, 0],
[ 7, 0, 0, 8, 0, 3, 0, 0, 2],
[ 0, 0, 0, 0, 0, 0, 3, 0, 8],
[ 0, 7, 8, 0, 2, 5, 6, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 2, 3, 4, 0, 1, 8, 0],
[ 8, 0, 9, 0, 0, 0, 0, 0, 0],
[ 5, 0, 0, 4, 0, 1, 0, 0, 9],
[ 0, 0, 1, 0, 5, 0, 0, 0, 4]
]
problem2 = [
[ 0, 8, 0, 0, 0, 3, 0, 0, 0],
[ 5, 0, 3, 0, 4, 0, 2, 0, 0],
[ 7, 0, 4, 0, 8, 0, 0, 0, 3],
[ 0, 7, 0, 0, 0, 0, 5, 0, 0],
[ 0, 3, 0, 8, 0, 5, 0, 6, 0],
[ 0, 0, 1, 0, 0, 0, 0, 9, 0],
[ 9, 0, 0, 0, 3, 0, 7, 0, 6],
[ 0, 0, 7, 0, 2, 0, 3, 0, 1],
[ 0, 0, 0, 6, 0, 0, 0, 2, 0]
]
problem = problem2
# problem = problem2
# define the problem variables
# Hint: three dimentional array
V = [ [ [Bool("x_{}_{}_{}".format(i,j,k)) for k in range(9)] for j in range(9)] for i in range(9)]
# print(V)
def sum_to_one( ls ):
A = Or(ls)
atmost_one_list = []
for pair in itertools.combinations(ls,2):
atmost_one_list.append(Or(Not(pair[0]),Not(pair[1])))
return And(A, And(atmost_one_list))
# Accumulate constraints in the following list
Fs = []
# Encode already filled positions
A = True
for i in range(9):
for j in range(9):
if problem[i][j]:
A = And(A, V[i][j][problem[i][j]-1])
Fs.append(A)
# Encode for i,j \sum_k x_i_j_k = 1
B = True
for i in range(9):
for j in range(9):
B = And(B, sum_to_one(V[i][j]))
Fs.append(B)
# Encode for j,k \sum_i x_i_j_k = 1
C = True
for j in range(9):
for k in range(9):
l = []
for i in range(9):
l.append(V[i][j][k])
C = And(C, sum_to_one(l))
Fs.append(C)
# Encode for i,k \sum_j x_i_j_k = 1
D = True
for i in range(9):
for k in range(9):
l = []
for j in range(9):
l.append(V[i][j][k])
D = And(D, sum_to_one(l))
Fs.append(D)
# Encode for i,j,k \sum_r_s x_3i+r_3j+s_k = 1
E = True
for p in [0,3,6]:
for pp in [0,3,6]:
for k in range(9):
l = []
for i in range(3):
for j in range(3):
l.append(V[i+p][j+pp][k])
E = And(E,sum_to_one(l))
Fs.append(E)
s = Solver()
s.add( And( Fs ) )
if s.check() == sat:
m = s.model()
for i in range(9):
if i % 3 == 0 :
print( "|------|------|------|")
for j in range(9):
if j % 3 == 0 :
print ("|",end="")
for k in range(9):
# FILL THE GAP
# val model for the variables
val = m[V[i][j][k]]
if is_true( val ):
print ("{}".format(k+1),end=",")
# if problem[i][j]:
# print("{}".format(problem[i][j]),end=",")
print ("|,")
print ("|------|------|------|")
else:
print ("sudoku is unsat")