瀏覽代碼

Fixed shit.

Stocarson 9 年之前
父節點
當前提交
fdbed44c9a
共有 1 個文件被更改,包括 23 次插入5 次删除
  1. 23 5
      csp_solver.py

+ 23 - 5
csp_solver.py

@@ -4,6 +4,7 @@ from sudoku import Game
 from copy import deepcopy
 
 MAX_V = 9
+
 class State:
 
     def __init__(self):
@@ -16,9 +17,9 @@ class State:
         self.resultboard = resultboard
 
         choicesboard = []
-        numbers = set()
+        numbers = []
         for value in range(1,10):
-            numbers.add(value)
+            numbers.append(value)
         for x in range(MAX_V):
             row = []
             for y in range(MAX_V):
@@ -28,6 +29,17 @@ class State:
             choicesboard.append(newrow)
         self.choicesboard = choicesboard
 
+    def printBoard(self):
+        for x in range(MAX_V):
+            if x%3==0:
+                print()
+            for y in range(MAX_V):
+                if y%3==0:
+                    print(" ", end="")
+                print(self.resultboard[x][y], end="")
+            print()
+        print()
+
 def actions(state):
     actions = []
     for row in range(MAX_V):
@@ -61,19 +73,25 @@ def eliminateIllValues(state):
                 num = newState.resultboard[col][row]
                 # Eliminate duplicates numbers in a row
                 for x in range(MAX_V):
-                    newState.choicesboard[x][row].remove(num)
+                    softRemove(newState.choicesboard[x][row], num)
                     # Eliminate duplicates numbers in a column
                 for y in range(MAX_V):
-                    newState.choicesboard[col][y].remove(num)
+                    softRemove(newState.choicesboard[col][y], num)
                     # Eliminate duplicates in block (working only for 9x9 cells)
                 #for y in range(MAX_V)
                 #    choicesboard[col][y].del(state.resultboard[col][row])
     return newState
 
+def softRemove(list, target):
+    for item in list:
+        if item == target:
+            list.remove(item)
+
 if __name__ == "__main__":
     node = State()
-    while not goalTest(node):
+    while not goalTest(node) and len(actions(node)) is not 0:
         move = actions(node).pop()
         node = result(node,move)
         node = eliminateIllValues(node)
     print('Result found!')
+    node.printBoard()