-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCS3243_P2_Sudoku_f2.py
249 lines (214 loc) · 8.97 KB
/
CS3243_P2_Sudoku_f2.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
# CS3243 Introduction to Artificial Intelligence
# Project 2, Part 1: Sudoku
import sys
import copy
from collections import deque
from time import time
# Running script: given code can be run with the command:
# python file.py, ./path/to/init_state.txt ./output/output.txt
class Sudoku(object):
def __init__(self, puzzle):
# you may add more attributes if you need
self.puzzle = puzzle # self.puzzle is a list of lists
self.ans = copy.deepcopy(puzzle) # self.ans is a list of lists
self.csp = CSP(puzzle)
def solve(self):
self.AC3(self.csp)
assignment = self.backtrackingSearch(self.csp)
for var in assignment:
(i, j) = var.coordinate
self.ans[i][j] = assignment[var]
# self.ans is a list of lists
return self.ans
def backtrackingSearch(self, csp):
assignment = csp.inferAssignment()
return self.backtrack(csp, assignment)
def backtrack(self, csp, assignment = dict()):
if self.complete(assignment,csp):
return assignment
var = self.mrv(csp, assignment)
for value in csp.currDomains[var].copy():
if self.isConsistent(var, value, assignment, csp):
assignment[var] = value
#print(var)
csp.unassignedVars.remove(var)
removals = self.assume(var, value, csp)
# self.printAssignment(assignment)
# inferences = self.inference(csp, var, value)
if self.forwardChecking(var, value, assignment, removals,csp):
result = self.backtrack(csp, assignment)
if result:
return result
csp.unassignedVars.add(var)
self.addBack(removals,csp)
if var in assignment:
del assignment[var]
# del inferences from assignment
return False
def forwardChecking(self, var, val, assignment, removals, csp):
# csp.copyCurrDomain()
for N in csp.neighbour[var]:
if N not in assignment:
for value in csp.currDomains[N].copy():
if csp.constraints[(var,N)](val,value):
csp.currDomains[N].remove(value)
removals.append((N,value))
if not csp.currDomains[N]:
return False
return True
def assume(self, var, value, csp):
# csp.copyCurrDomain()
removals = list()
for val in csp.currDomains[var]:
if val != value:
removals.append((var,val))
csp.currDomains[var] = {value}
return removals
def addBack(self, removals, csp):
for (var,val) in removals:
csp.currDomains[var].add(val)
def complete(self, assignment,csp):
return len(assignment) == len(csp.variables)
def isConsistent(self,var, val, assignment, csp):
for key in assignment:
if (var,key) in csp.constraints:
if csp.constraints[(var,key)](val,assignment[key]):
return False
return True
def mrv(self,csp,assignment): # minimum remaining values
# seq = csp.unassignedVars.copy() #filter(lambda var: var not in assignment,csp.variables)
return min(csp.unassignedVars.copy(),key=lambda var: len(csp.currDomains[var]))
def AC3(self,csp):
arcs = set()
for cons in csp.constraints:
arcs.add(cons)
csp.copyCurrDomain()
while arcs:
(xi, xj) = arcs.pop()
if self.revise(csp, xi, xj):
if not csp.currDomains[xi]:
return False
# for xk in csp.neighbour[xi]:
# if xk != xj:
arcs |= {(xk, xi) for xk in csp.neighbour[xi] if xk != xj and (xk, xi not in arcs)}
return True
def revise(self, csp, xi, xj):
length = len(csp.currDomains[xi])
if len(csp.currDomains[xj]) == 1:
csp.currDomains[xi]-=csp.currDomains[xj]
if len(csp.currDomains[xi])< length:
return True
return False
# revised = False
# print("before xi:",csp.currDomains[xi])
# print("before xj:",csp.currDomains[xj])
# for x in csp.currDomains[xi].copy():
# conflict = True
# #if any(map(lambda y : csp.constraints[(xi, xj)](x, y),csp.currDomains[xj])):
# #xi.domain.remove(x)
# for y in csp.currDomains[xj]:
# if not csp.constraints[(xi,xj)](x,y):
# conflict = False
# if not conflict:
# break
# if conflict:
# csp.currDomains[xi].remove(x)
# revised = True
# if revised:
# print("after",csp.currDomains[xi])
# print("------------------------")
# return revised
# you may add more classes/functions if you think is useful
# However, ensure all the classes/functions are in this file ONLY
# Note that our evaluation scripts only call the solve method.
# Any other methods that you write should be used within the solve() method.
class Variable(object):
def __init__(self, coordinate, value):
self.coordinate = coordinate # (x, y)
self.value = value
def __hash__(self):
return hash(self.coordinate)
def __eq__(self, var):
return self.coordinate == var.coordinate
def __str__(self):
return str(self.coordinate)
def isSameUnit(self, var):
return self.isSameRow(var) or self.isSameCol(var) or self.isSameSquare(var)
def isSameRow(self, var):
return self.coordinate[0] == var.coordinate[0]
def isSameCol(self, var):
return self.coordinate[1] == var.coordinate[1]
def isSameSquare(self, var):
''' square refers to 3*3 square '''
return (self.coordinate[0]//3, self.coordinate[1]//3) == (var.coordinate[0]//3, var.coordinate[1]//3)
class CSP(object):
def __init__(self, puzzle): #removed constraints
self.variables = set() # set of var
self.domains = dict() # key = var, value = var_domain (set)
self.neighbour = dict() # key = var, value = var_neighbour (set)
# set of binary constraints (constraint function involving two var) represented by pair(scope, relation)
# scope = (x, y), relation = f(x, y), where x, y are vars
self.constraints = dict()
self.initialiseCSP(puzzle)
self.unassignedVars = self.variables.copy()
self.currDomains = None
def initialiseCSP(self,puzzle): #initialise csp
# going through 2d list
# for i in range(9):
# for j in range(9):
self.variables = set((Variable((i, j), puzzle[i][j]) for i in range(9) for j in range(9)))
# going through var set
for var1 in self.variables:
self.domains[var1] = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) if not var1.value else set([var1.value])
self.neighbour[var1] = set()
for var2 in self.variables:
if var1 != var2 and var1.isSameUnit(var2):
self.constraints[(var1, var2)] = lambda x,y: x==y #to check if in conflict
self.neighbour[var1].add(var2)
def copyCurrDomain(self):
''' Create a copy of domains as currDomains '''
if self.currDomains is None:
self.currDomains = {var : set(self.domains[var]) for var in self.variables}
# for var in self.variables:
# self.currDomains[var] = {i for i in self.domains[var]}
def inferAssignment(self):
assignment = {}
#print("infer assignment")
#self.copyCurrDomain()
for var in self.currDomains:
if len(self.currDomains[var])==1:
assignment[var] = list(self.currDomains[var])[0]
self.unassignedVars.remove(var)
return assignment
if __name__ == "__main__":
# STRICTLY do NOT modify the code in the main function here
if len(sys.argv) != 3:
print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n")
raise ValueError("Wrong number of arguments!")
try:
f = open(sys.argv[1], 'r')
except IOError:
print ("\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\n")
raise IOError("Input file not found!")
puzzle = [[0 for i in range(9)] for j in range(9)]
lines = f.readlines()
i, j = 0, 0
for line in lines:
for number in line:
if '0' <= number <= '9':
puzzle[i][j] = int(number)
j += 1
if j == 9:
i += 1
j = 0
sudoku = Sudoku(puzzle)
start = time()
ans = sudoku.solve()
end = time()
# outfile.close()
# print(ans)
with open(sys.argv[2], 'a') as f:
for i in range(9):
for j in range(9):
f.write(str(ans[i][j]) + " ")
f.write("\n")