csp_solver.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. from sudoku import Game
  3. MAX_V = 9
  4. class State:
  5. def __init__(self):
  6. resultboard = []
  7. for x in range(MAX_V):
  8. temprow = []
  9. for y in range(MAX_V):
  10. temprow.append(0)
  11. resultboard.append(temprow)
  12. self.resultboard = resultboard
  13. choicesboard = []
  14. # Populate the numbers vector with values from 1 to MAX_V
  15. # choicesboard is a bidimensional list with numbers for every element
  16. for x in range(MAX_V):
  17. row = []
  18. for y in range(MAX_V):
  19. numbers = set()
  20. for value in range(1,10):
  21. numbers.add(value)
  22. row.append(numbers)
  23. choicesboard.append(row)
  24. self.choicesboard = choicesboard
  25. def actions(state):
  26. actions = []
  27. for row in range(MAX_V):
  28. for col in range(MAX_V):
  29. #Value not yet assigned
  30. if state.resultboard[col][row] == 0:
  31. #Add possible move
  32. for num in state.choicesboard[col][row]:
  33. move = {'col': col, 'row': row, 'num': num}
  34. actions.append(move)
  35. return actions
  36. def result(state,move):
  37. state.resultboard[move['col']][move['row']] = move['num']
  38. def goalTest(state):
  39. incomplete = False
  40. for row in range(MAX_V):
  41. for col in range(MAX_V):
  42. if state.resultboard[col][row] == 0:
  43. imcomplete = True
  44. return incomplete
  45. def eliminateIllValues(state):
  46. for row in range(MAX_V):
  47. for col in range(MAX_V):
  48. if state.resultboard[col][row] != 0:
  49. num = state.resultboard[col][row]
  50. # Eliminate duplicates numbers in a row
  51. for x in range(MAX_V):
  52. state.choicesboard[x][row].remove(num)
  53. # Eliminate duplicates numbers in a column
  54. for y in range(MAX_V):
  55. state.choicesboard[col][y].remove(num)
  56. # Eliminate duplicates in block (working only for 9x9 cells)
  57. #for y in range(MAX_V)
  58. # choicesboard[col][y].del(state.resultboard[col][row])
  59. if __name__ == "__main__":
  60. node = State()
  61. while not goalTest(node):
  62. move=actions(node).pop()
  63. result(node,move)
  64. eliminateIllValues(node)
  65. print('Result found!')