csp_solver.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 = set()
  16. for value in range(1,10):
  17. numbers.add(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 actions(state):
  27. actions = []
  28. for row in range(MAX_V):
  29. for col in range(MAX_V):
  30. #Value not yet assigned
  31. if state.resultboard[col][row] == 0:
  32. #Add possible move
  33. for num in state.choicesboard[col][row]:
  34. move = {'col': col, 'row': row, 'num': num}
  35. actions.append(move)
  36. return actions
  37. def result(state,move):
  38. newState = deepcopy(state)
  39. newState.resultboard[move['col']][move['row']] = move['num']
  40. return newState
  41. def goalTest(state):
  42. incomplete = False
  43. for row in range(MAX_V):
  44. for col in range(MAX_V):
  45. if state.resultboard[col][row] == 0:
  46. imcomplete = True
  47. return incomplete
  48. def eliminateIllValues(state):
  49. newState = deepcopy(state)
  50. for row in range(MAX_V):
  51. for col in range(MAX_V):
  52. if newState.resultboard[col][row] != 0:
  53. num = newState.resultboard[col][row]
  54. # Eliminate duplicates numbers in a row
  55. for x in range(MAX_V):
  56. newState.choicesboard[x][row].remove(num)
  57. # Eliminate duplicates numbers in a column
  58. for y in range(MAX_V):
  59. newState.choicesboard[col][y].remove(num)
  60. # Eliminate duplicates in block (working only for 9x9 cells)
  61. #for y in range(MAX_V)
  62. # choicesboard[col][y].del(state.resultboard[col][row])
  63. return newState
  64. if __name__ == "__main__":
  65. node = State()
  66. while not goalTest(node):
  67. move = actions(node).pop()
  68. node = result(node,move)
  69. node = eliminateIllValues(node)
  70. print('Result found!')