csp_solver.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/env python3
  2. from sudoku import Game
  3. from copy import deepcopy
  4. MAX_V = 9
  5. class State:
  6. def __init__(self):
  7. resultboard = []
  8. for x in range(MAX_V):
  9. temprow = []
  10. for y in range(MAX_V):
  11. temprow.append(0)
  12. resultboard.append(temprow)
  13. self.resultboard = resultboard
  14. choicesboard = []
  15. numbers = []
  16. for value in range(1,10):
  17. numbers.append(value)
  18. for x in range(MAX_V):
  19. row = []
  20. for y in range(MAX_V):
  21. choices = deepcopy(numbers)
  22. row.append(choices)
  23. newrow=deepcopy(row)
  24. choicesboard.append(newrow)
  25. self.choicesboard = choicesboard
  26. def printBoard(self):
  27. for x in range(MAX_V):
  28. if x%3==0:
  29. print()
  30. for y in range(MAX_V):
  31. if y%3==0:
  32. print(" ", end="")
  33. print(self.resultboard[x][y], end="")
  34. print()
  35. print()
  36. def actions(state):
  37. actions = []
  38. for row in range(MAX_V):
  39. for col in range(MAX_V):
  40. #Value not yet assigned
  41. if state.resultboard[col][row] == 0:
  42. #Add possible move
  43. for num in state.choicesboard[col][row]:
  44. move = {'col': col, 'row': row, 'num': num}
  45. actions.append(move)
  46. return actions
  47. def result(state,move):
  48. newState = deepcopy(state)
  49. newState.resultboard[move['col']][move['row']] = move['num']
  50. return newState
  51. def goalTest(state):
  52. incomplete = False
  53. for row in range(MAX_V):
  54. for col in range(MAX_V):
  55. if state.resultboard[col][row] == 0:
  56. imcomplete = True
  57. return incomplete
  58. def eliminateIllValues(state):
  59. newState = deepcopy(state)
  60. for row in range(MAX_V):
  61. for col in range(MAX_V):
  62. if newState.resultboard[col][row] != 0:
  63. num = newState.resultboard[col][row]
  64. # Eliminate duplicates numbers in a row
  65. for x in range(MAX_V):
  66. softRemove(newState.choicesboard[x][row], num)
  67. # Eliminate duplicates numbers in a column
  68. for y in range(MAX_V):
  69. softRemove(newState.choicesboard[col][y], num)
  70. # Eliminate duplicates in block (working only for 9x9 cells)
  71. #for y in range(MAX_V)
  72. # choicesboard[col][y].del(state.resultboard[col][row])
  73. return newState
  74. def softRemove(list, target):
  75. for item in list:
  76. if item == target:
  77. list.remove(item)
  78. if __name__ == "__main__":
  79. node = State()
  80. while not goalTest(node) and len(actions(node)) is not 0:
  81. move = actions(node).pop()
  82. node = result(node,move)
  83. node = eliminateIllValues(node)
  84. print('Result found!')
  85. node.printBoard()