sudoku.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import sys
  2. import copy
  3. from contextlib import suppress
  4. from heapq import heappush, heappop
  5. board = sys.argv[1]
  6. algotype = sys.argv[2]
  7. # import board
  8. with open(board) as file:
  9. board = file.read().splitlines()
  10. board = board[:-1]
  11. # convert to list of list of ints
  12. for l in board:
  13. board[board.index(l)] = list(map(lambda x: int(x), l.split()))
  14. # return a board that is like the board b, but has domains for each element of b (always 1-9)
  15. def genDomains(b):
  16. for row in range(0, 9):
  17. for cell in range(0, 9):
  18. if (b[row][cell] == 0):
  19. b[row][cell] = list(range(1, 10))
  20. return b
  21. # returns True if value is valid
  22. def valid(brd, row, col, val):
  23. # check row
  24. if (val in brd[row]):
  25. return False
  26. # check column
  27. for i in range(0, 9):
  28. if (brd[i][col] == val):
  29. return False
  30. # check "box"
  31. rownum = int(row / 3)
  32. colnum = int(col / 3)
  33. for i in range(rownum * 3, rownum * 3 + 3):
  34. for j in range(colnum * 3, colnum * 3 + 3):
  35. if (brd[i][j] == val):
  36. return False
  37. return True
  38. # naive backtracking solver
  39. def naive(start):
  40. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  41. solution = genDomains(start)
  42. # unassigned will be a list of positions we have to fill
  43. unassigned = []
  44. for i in range(0, 9):
  45. for j in range(0, 9):
  46. if (isinstance(solution[i][j], list)):
  47. unassigned.append((i, j))
  48. assumptions = []
  49. if(len(unassigned) == 0):
  50. return True
  51. while(len(unassigned)):
  52. index = unassigned[-1]
  53. success = False
  54. # iterate over all values in the domain list
  55. while solution[index[0]][index[1]]:
  56. i = solution[index[0]][index[1]].pop()
  57. if (valid(working, index[0], index[1], i)):
  58. solution[index[0]][index[1]].append(i) # keep in the domain
  59. working[index[0]][index[1]] = i
  60. assumptions.append(index)
  61. unassigned.pop()
  62. success = True
  63. break
  64. if (success):
  65. continue
  66. else:
  67. # restore domain to full since we failed
  68. solution[index[0]][index[1]] = list(range(1, 10))
  69. working[index[0]][index[1]] = 0
  70. lastdex = assumptions.pop()
  71. solution[lastdex[0]][lastdex[1]].remove(working[lastdex[0]][lastdex[1]])
  72. working[lastdex[0]][lastdex[1]] = 0
  73. unassigned.append(lastdex)
  74. if (unassigned): return False
  75. return working
  76. # returns a board (domains) where inferences are made for the cell at row, col
  77. def infer(solutions, brd, row, col, val):
  78. domains = copy.deepcopy(solutions)
  79. # remove from same row & col
  80. for i in range(0, 9):
  81. if (val in domains[row][i] and i != col):
  82. domains[row][i].remove(val)
  83. if (val in domains[i][col] and i != row):
  84. domains[i][col].remove(val)
  85. # remove for "box"
  86. rownum = int(row / 3)
  87. colnum = int(col / 3)
  88. for i in range(rownum * 3, rownum * 3 + 3):
  89. for j in range(colnum * 3, colnum * 3 + 3):
  90. if (val in domains[i][j] and (i != row and j != col)):
  91. domains[i][j].remove(val)
  92. return domains
  93. # generates domains in a format supporting forward checking
  94. def gen2Domains(b):
  95. for row in range(0, 9):
  96. for cell in range(0, 9):
  97. if (b[row][cell] == 0):
  98. b[row][cell] = list(range(1, 10))
  99. else:
  100. b[row][cell] = [b[row][cell]]
  101. return b
  102. # recursive solver for forward-checking
  103. def solve(working, domains, unassigned):
  104. if (not unassigned):
  105. return working
  106. index = unassigned.pop()
  107. for i in domains[index[0]][index[1]]:
  108. working[index[0]][index[1]] = i
  109. newdomains = infer(domains, working, index[0], index[1], i)
  110. result = solve(working, newdomains, copy.deepcopy(unassigned))
  111. if (result):
  112. return result
  113. else:
  114. continue
  115. return False
  116. # forward checking solver
  117. def forward(start):
  118. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  119. domains = gen2Domains(start)
  120. # unassigned will be a list of positions we have to fill
  121. unassigned = []
  122. for i in range(0, 9):
  123. for j in range(0, 9):
  124. if (len(domains[i][j]) == 9):
  125. unassigned.append((i, j))
  126. for i in range(0, 9):
  127. for j in range(0, 9):
  128. if (working[i][j] != 0):
  129. domains = infer(domains, working, i, j, working[i][j])
  130. return solve(working, domains, unassigned)
  131. # returns size of domain for a given index
  132. def domsize(domains, index):
  133. return (len(domains[index[0]][index[1]]))
  134. # returns the # of 0s that are in the same row, col, or box as index
  135. def related(brd, index):
  136. count = 0
  137. # count 0s in row + col
  138. for i in range(0, 9):
  139. if (brd[index[0]][i] == 0 and i != index[1]):
  140. ++count
  141. if (brd[i][index[1]] == 0 and i != index[0]):
  142. ++count
  143. # count for "box" as well
  144. rownum = int(index[0] / 3)
  145. colnum = int(index[1] / 3)
  146. for i in range(rownum * 3, rownum * 3 + 3):
  147. for j in range(colnum * 3, colnum * 3 + 3):
  148. if (brd[i][j] == 0 and (i != index[0] and j != index[1])):
  149. ++count
  150. return count
  151. # returns the # of constraints that will follow from assigning index with val
  152. def lcv(solutions, index, val):
  153. count = 0
  154. # count 0s in row + col
  155. for i in range(0, 9):
  156. if (val in solutions[index[0]][i] and i != index[1]):
  157. ++count
  158. if (val in solutions[i][index[1]] and i != index[0]):
  159. ++count
  160. # count for "box" as well
  161. rownum = int(index[0] / 3)
  162. colnum = int(index[1] / 3)
  163. for i in range(rownum * 3, rownum * 3 + 3):
  164. for j in range(colnum * 3, colnum * 3 + 3):
  165. if (val in solutions[i][j] and (i != index[0] and j != index[1])):
  166. ++count
  167. return count
  168. # return the correct node + val to try
  169. def genVal(domains, working, unassigned):
  170. heap = []
  171. superheap = []
  172. bestrating = 1.0
  173. # get the best indices according to domain size
  174. for i in unassigned:
  175. rating = domsize(domains, i) / 9.0
  176. if (rating == 0):
  177. print(i)
  178. if (rating < bestrating):
  179. bestrating = rating
  180. heap = [i]
  181. elif (rating == bestrating):
  182. heap.append(i)
  183. # get the best indices according to degree(related cells)
  184. bestrating = 1
  185. for i in heap:
  186. rating = related(working, i) / 27.0
  187. if (rating < bestrating):
  188. bestrating = rating
  189. superheap = [i]
  190. elif (rating == bestrating):
  191. superheap.append(i)
  192. index = superheap[0]
  193. bestrating = 27
  194. val = working[index[0]][index[1]]
  195. # get best values according to LCV
  196. for i in domains[index[0]][index[1]]:
  197. rating = lcv(domains, index, i)
  198. if (rating <= bestrating):
  199. bestrating = rating
  200. val = i
  201. return (index, val)
  202. # recursive solver that uses heuristics to decide what node to explore
  203. def solveh(working, domains, unassigned):
  204. if (not unassigned):
  205. return working
  206. while(unassigned):
  207. nextThing = genVal(domains, working, unassigned)
  208. index = nextThing[0]
  209. val = nextThing[1]
  210. working[index[0]][index[1]] = val
  211. unassigned.remove(index)
  212. if (index == (8, 8)):
  213. print("value is: ", val)
  214. # check for invalidated nodes (empty domain)
  215. flag = True
  216. result = False
  217. newdomains = infer(domains, working, index[0], index[1], val)
  218. for i in range(0, 9):
  219. for j in range(0, 9):
  220. if (not domains[i][j]):
  221. flag = False
  222. if (flag): result = solveh(working, newdomains, copy.deepcopy(unassigned))
  223. if (result):
  224. return result
  225. elif (len(domains[index[0]][index[1]]) > 1):
  226. working[index[0]][index[1]] = 0
  227. domains[index[0]][index[1]].remove(val)
  228. unassigned.append(index)
  229. else:
  230. return False
  231. # forward checking solver with heuristics
  232. def heuristic(start):
  233. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  234. domains = gen2Domains(start)
  235. # unassigned will be a list of positions we have to fill
  236. unassigned = []
  237. for i in range(0, 9):
  238. for j in range(0, 9):
  239. if (len(domains[i][j]) == 9):
  240. unassigned.append((i, j))
  241. for i in range(0, 9):
  242. for j in range(0, 9):
  243. if (working[i][j] != 0):
  244. domains = infer(domains, working, i, j, working[i][j])
  245. return solveh(working, domains, unassigned)
  246. def main():
  247. print("###########")
  248. print(*board, sep='\n')
  249. print("##########")
  250. if (algotype == str(0)):
  251. result = naive(board)
  252. elif (algotype == str(1)):
  253. result = forward(board)
  254. elif (algotype == str(2)):
  255. result = heuristic(board)
  256. else:
  257. print("No valid algorithm selected. RIP.")
  258. print("###########")
  259. print(*result, sep='\n')
  260. print("##########")
  261. main()