|
@@ -61,6 +61,7 @@ def naive(start):
|
|
|
if(len(unassigned) == 0):
|
|
|
return True
|
|
|
|
|
|
+ # while there are unassigned vars, keep going
|
|
|
while(len(unassigned)):
|
|
|
index = unassigned[-1]
|
|
|
success = False
|
|
@@ -68,6 +69,7 @@ def naive(start):
|
|
|
# iterate over all values in the domain list
|
|
|
while solution[index[0]][index[1]]:
|
|
|
i = solution[index[0]][index[1]].pop()
|
|
|
+ # check if this part of the domain(solution) is valid
|
|
|
if (valid(working, index[0], index[1], i)):
|
|
|
solution[index[0]][index[1]].append(i) # keep in the domain
|
|
|
working[index[0]][index[1]] = i
|
|
@@ -88,6 +90,7 @@ def naive(start):
|
|
|
unassigned.append(lastdex)
|
|
|
|
|
|
|
|
|
+ # if we exit without assigning everything, we should have failed
|
|
|
if (unassigned): return False
|
|
|
|
|
|
return working
|
|
@@ -133,6 +136,7 @@ def solve(working, domains, unassigned):
|
|
|
|
|
|
index = unassigned.pop()
|
|
|
|
|
|
+ # for every value in the domain, check if using it works. if all fail, backtrack.
|
|
|
for i in domains[index[0]][index[1]]:
|
|
|
working[index[0]][index[1]] = i
|
|
|
newdomains = infer(domains, working, index[0], index[1], i)
|
|
@@ -155,6 +159,7 @@ def forward(start):
|
|
|
if (len(domains[i][j]) == 9):
|
|
|
unassigned.append((i, j))
|
|
|
|
|
|
+ # forward-checking on pre-assigned values
|
|
|
for i in range(0, 9):
|
|
|
for j in range(0, 9):
|
|
|
if (working[i][j] != 0):
|
|
@@ -214,6 +219,7 @@ def lcv(solutions, index, val):
|
|
|
|
|
|
# return the correct node + val to try
|
|
|
def genVal(domains, working, unassigned):
|
|
|
+ # used to track intermediary values
|
|
|
heap = []
|
|
|
superheap = []
|
|
|
bestrating = 1.0
|
|
@@ -256,7 +262,9 @@ def solveh(working, domains, unassigned):
|
|
|
if (not unassigned):
|
|
|
return working
|
|
|
|
|
|
+ # while there are unassigned values keep trying
|
|
|
while(unassigned):
|
|
|
+ # get next value using heuristics, remove this node from assigned
|
|
|
nextThing = genVal(domains, working, unassigned)
|
|
|
index = nextThing[0]
|
|
|
val = nextThing[1]
|
|
@@ -272,14 +280,15 @@ def solveh(working, domains, unassigned):
|
|
|
if (not domains[i][j]):
|
|
|
flag = False
|
|
|
|
|
|
+ # success! recurse
|
|
|
if (flag): result = solveh(working, newdomains, copy.deepcopy(unassigned))
|
|
|
if (result):
|
|
|
return result
|
|
|
- elif (len(domains[index[0]][index[1]]) > 1):
|
|
|
+ elif (len(domains[index[0]][index[1]]) > 1): # remove from domain, keep going
|
|
|
working[index[0]][index[1]] = 0
|
|
|
domains[index[0]][index[1]].remove(val)
|
|
|
unassigned.append(index)
|
|
|
- else:
|
|
|
+ else: # no values worked :( return false
|
|
|
return False
|
|
|
|
|
|
|
|
@@ -294,6 +303,7 @@ def heuristic(start):
|
|
|
if (len(domains[i][j]) == 9):
|
|
|
unassigned.append((i, j))
|
|
|
|
|
|
+ # initial inferences
|
|
|
for i in range(0, 9):
|
|
|
for j in range(0, 9):
|
|
|
if (working[i][j] != 0):
|