-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsp_problems.py
199 lines (175 loc) · 7 KB
/
csp_problems.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
from csp import Constraint, Variable, CSP
from constraints import *
from backtracking import bt_search
import util
def nQueens(n, tableCnstr):
'''Return an n-queens CSP, optionally use tableContraints'''
i = 0
dom = []
for i in range(n):
dom.append(i+1)
vars = []
for i in dom:
vars.append(Variable('Q{}'.format(i), dom))
cons = []
for qi in range(len(dom)):
for qj in range(qi+1, len(dom)):
if tableCnstr:
con = QueensTableConstraint("C(Q{},Q{})".format(qi+1,qj+1),
vars[qi], vars[qj], qi+1, qj+1)
else: con = QueensConstraint("C(Q{},Q{})".format(qi+1,qj+1),
vars[qi], vars[qj], qi+1, qj+1)
cons.append(con)
csp = CSP("{}-Queens".format(n), vars, cons)
return csp
def solve_nQueens(n, algo, allsolns, tableCnstr=False, variableHeuristic='fixed', trace=False):
'''Create and solve an nQueens CSP problem. The first
parameer is 'n' the number of queens in the problem,
The second specifies the search algorithm to use (one
of 'BT', 'FC', or 'GAC'), the third specifies if
all solutions are to be found or just one, variableHeuristic
specfies how the next variable is to be selected
'random' at random, 'fixed' in a fixed order, 'mrv'
minimum remaining values. Finally 'trace' if specified to be
'True' will generate some output as the search progresses.
'''
csp = nQueens(n, tableCnstr)
solutions, num_nodes = bt_search(algo, csp, variableHeuristic, allsolns, trace)
print "Explored {} nodes".format(num_nodes)
if len(solutions) == 0:
print "No solutions to {} found".format(csp.name())
else:
print "Solutions to {}:".format(csp.name())
i = 0
for s in solutions:
i += 1
print "Solution #{}: ".format(i),
for (var,val) in s:
print "{} = {}, ".format(var.name(),val),
print ""
def sudokuCSP(initial_sudoku_board, model='neq'):
'''The input board is specified as a list of 9 lists. Each of the
9 lists represents a row of the board. If a 0 is in the list it
represents an empty cell. Otherwise if a number between 1--9 is
in the list then this represents a pre-set board
position. E.g., the board
-------------------
| | |2| |9| | |6| |
| |4| | | |1| | |8|
| |7| |4|2| | | |3|
|5| | | | | |3| | |
| | |1| |6| |5| | |
| | |3| | | | | |6|
|1| | | |5|7| |4| |
|6| | |9| | | |2| |
| |2| | |8| |1| | |
-------------------
would be represented by the list of lists
[[0,0,2,0,9,0,0,6,0],
[0,4,0,0,0,1,0,0,8],
[0,7,0,4,2,0,0,0,3],
[5,0,0,0,0,0,3,0,0],
[0,0,1,0,6,0,5,0,0],
[0,0,3,0,0,0,0,0,6],
[1,0,0,0,5,7,0,4,0],
[6,0,0,9,0,0,0,2,0],
[0,2,0,0,8,0,1,0,0]]
Construct and return CSP for solving this sudoku board using
binary not equals if model='neq' or using allDiff constraints
if model='alldiff'
The CSP contains a variable for each cell of the board with
with domain equal to {1-9} if the board has a 0 at that position,
and domain equal {i} if the board has a fixed number i at that
cell.
The CSP has a neq constraint between every relevant pair of
varibles, or an alldiff constraint between every set of
variables in a row, column, or sub-square
'''
#your implementation for Question 4 changes this function
#implement handleing of model == 'alldiff'
if not model in ['neq', 'alldiff']:
print "Error wrong sudoku model specified {}. Must be one of {}".format(
model, ['neq', 'alldiff'])
#first define the variables
i = 0
var_array = []
for row_list in initial_sudoku_board:
var_array.append([])
j = 0
for col in row_list:
cell = initial_sudoku_board[i][j]
if cell == 0:
dom = [1, 2, 3, 4, 5, 6, 7, 8, 9]
else:
dom = [cell]
var = Variable("V{},{}".format(i+1, j+1), dom)
var_array[i].append(var)
j += 1
i += 1
#Set up the constraints
#row constraints
constraint_list = []
for row in var_array:
if model == 'neq':
constraint_list.extend(post_all_pairs(row))
elif model == 'alldiff':
# util.raiseNotDefined()
constraint_list.append(AllDiffConstraint("Row " + str(var_array.index(row)), row))
for colj in range(len(var_array[0])):
scope = map(lambda row: row[colj], var_array)
if model == 'neq':
constraint_list.extend(post_all_pairs(scope))
elif model == 'alldiff':
# util.raiseNotDefined()
constraint_list.append(AllDiffConstraint("Column " + str(colj), scope))
for i in [0, 3, 6]:
for j in [0, 3, 6]:
#initial upper left hand index of subsquare
scope = []
for k in [0, 1, 2]:
for l in [0,1,2]:
scope.append(var_array[i+k][j+l])
if model == 'neq':
constraint_list.extend(post_all_pairs(scope))
elif model == 'alldiff':
# util.raiseNotDefined()
constraint_list.append(AllDiffConstraint("SubSquare " + str(i // 3) + " " + str(j // 3), scope))
vars = [var for row in var_array for var in row]
return CSP("Sudoku", vars, constraint_list)
def post_all_pairs(var_list):
'''create a not equal constraint between all pairs of variables in var_list
return list of constructed constraint objects'''
constraints = []
for i in range(len(var_list)):
for j in range(i+1,len(var_list)):
c = NeqConstraint("({},{})".format(var_list[i].name(), var_list[j].name()),[var_list[i], var_list[j]])
constraints.append(c)
return constraints
def solve_sudoku(initialBoard, model, algo, allsolns,
variableHeuristic='fixed', trace=False):
if not model in ['neq', 'alldiff']:
print "Error wrong sudoku model specified {}. Must be one of {}".format(
model, ['neq', 'alldiff'])
csp = sudokuCSP(initialBoard, model)
solutions, num_nodes = bt_search(algo, csp, variableHeuristic, allsolns, trace)
print "Explored {} nodes".format(num_nodes)
if len(solutions) == 0:
print "No solutions to {} found".format(csp.name())
else:
i = 0
for s in solutions:
i += 1
print "Solution #{}: ".format(i)
sudoku_print_soln(s)
def sudoku_print_soln(s):
'''s is a list of (var,value) pairs. Organize them into
the right order and then print it in a board layout'''
s.sort(key=lambda varval_pair: varval_pair[0].name())
print "-"*37
for i in range(0,9):
print "|",
for j in range(0,9):
indx = i*9 + j
print s[indx][1], "|",
print ""
print "-"*37