sudoku.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 there are unassigned vars, keep going
  52. while(len(unassigned)):
  53. index = unassigned[-1]
  54. success = False
  55. # iterate over all values in the domain list
  56. while solution[index[0]][index[1]]:
  57. i = solution[index[0]][index[1]].pop()
  58. # check if this part of the domain(solution) is valid
  59. if (valid(working, index[0], index[1], i)):
  60. solution[index[0]][index[1]].append(i) # keep in the domain
  61. working[index[0]][index[1]] = i
  62. assumptions.append(index)
  63. unassigned.pop()
  64. success = True
  65. break
  66. if (success):
  67. continue
  68. else:
  69. # restore domain to full since we failed
  70. solution[index[0]][index[1]] = list(range(1, 10))
  71. working[index[0]][index[1]] = 0
  72. lastdex = assumptions.pop()
  73. solution[lastdex[0]][lastdex[1]].remove(working[lastdex[0]][lastdex[1]])
  74. working[lastdex[0]][lastdex[1]] = 0
  75. unassigned.append(lastdex)
  76. # if we exit without assigning everything, we should have failed
  77. if (unassigned): return False
  78. return working
  79. # returns a board (domains) where inferences are made for the cell at row, col
  80. def infer(solutions, brd, row, col, val):
  81. domains = copy.deepcopy(solutions)
  82. # remove from same row & col
  83. for i in range(0, 9):
  84. if (val in domains[row][i] and i != col):
  85. domains[row][i].remove(val)
  86. if (val in domains[i][col] and i != row):
  87. domains[i][col].remove(val)
  88. # remove for "box"
  89. rownum = int(row / 3)
  90. colnum = int(col / 3)
  91. for i in range(rownum * 3, rownum * 3 + 3):
  92. for j in range(colnum * 3, colnum * 3 + 3):
  93. if (val in domains[i][j] and (i != row and j != col)):
  94. domains[i][j].remove(val)
  95. return domains
  96. # generates domains in a format supporting forward checking
  97. def gen2Domains(b):
  98. for row in range(0, 9):
  99. for cell in range(0, 9):
  100. if (b[row][cell] == 0):
  101. b[row][cell] = list(range(1, 10))
  102. else:
  103. b[row][cell] = [b[row][cell]]
  104. return b
  105. # recursive solver for forward-checking
  106. def solve(working, domains, unassigned):
  107. if (not unassigned):
  108. return working
  109. index = unassigned.pop()
  110. # for every value in the domain, check if using it works. if all fail, backtrack.
  111. for i in domains[index[0]][index[1]]:
  112. working[index[0]][index[1]] = i
  113. newdomains = infer(domains, working, index[0], index[1], i)
  114. result = solve(working, newdomains, copy.deepcopy(unassigned))
  115. if (result):
  116. return result
  117. else:
  118. continue
  119. return False
  120. # forward checking solver
  121. def forward(start):
  122. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  123. domains = gen2Domains(start)
  124. # unassigned will be a list of positions we have to fill
  125. unassigned = []
  126. for i in range(0, 9):
  127. for j in range(0, 9):
  128. if (len(domains[i][j]) == 9):
  129. unassigned.append((i, j))
  130. # forward-checking on pre-assigned values
  131. for i in range(0, 9):
  132. for j in range(0, 9):
  133. if (working[i][j] != 0):
  134. domains = infer(domains, working, i, j, working[i][j])
  135. return solve(working, domains, unassigned)
  136. # returns size of domain for a given index
  137. def domsize(domains, index):
  138. return (len(domains[index[0]][index[1]]))
  139. # returns the # of 0s that are in the same row, col, or box as index
  140. def related(brd, index):
  141. count = 0
  142. # count 0s in row + col
  143. for i in range(0, 9):
  144. if (brd[index[0]][i] == 0 and i != index[1]):
  145. ++count
  146. if (brd[i][index[1]] == 0 and i != index[0]):
  147. ++count
  148. # count for "box" as well
  149. rownum = int(index[0] / 3)
  150. colnum = int(index[1] / 3)
  151. for i in range(rownum * 3, rownum * 3 + 3):
  152. for j in range(colnum * 3, colnum * 3 + 3):
  153. if (brd[i][j] == 0 and (i != index[0] and j != index[1])):
  154. ++count
  155. return count
  156. # returns the # of constraints that will follow from assigning index with val
  157. def lcv(solutions, index, val):
  158. count = 0
  159. # count 0s in row + col
  160. for i in range(0, 9):
  161. if (val in solutions[index[0]][i] and i != index[1]):
  162. ++count
  163. if (val in solutions[i][index[1]] and i != index[0]):
  164. ++count
  165. # count for "box" as well
  166. rownum = int(index[0] / 3)
  167. colnum = int(index[1] / 3)
  168. for i in range(rownum * 3, rownum * 3 + 3):
  169. for j in range(colnum * 3, colnum * 3 + 3):
  170. if (val in solutions[i][j] and (i != index[0] and j != index[1])):
  171. ++count
  172. return count
  173. # return the correct node + val to try
  174. def genVal(domains, working, unassigned):
  175. # used to track intermediary values
  176. heap = []
  177. superheap = []
  178. bestrating = 1.0
  179. # get the best indices according to domain size
  180. for i in unassigned:
  181. rating = domsize(domains, i) / 9.0
  182. if (rating < bestrating):
  183. bestrating = rating
  184. heap = [i]
  185. elif (rating == bestrating):
  186. heap.append(i)
  187. # get the best indices according to degree(related cells)
  188. bestrating = 1
  189. for i in heap:
  190. rating = related(working, i) / 27.0
  191. if (rating < bestrating):
  192. bestrating = rating
  193. superheap = [i]
  194. elif (rating == bestrating):
  195. superheap.append(i)
  196. index = superheap[0]
  197. bestrating = 27
  198. val = working[index[0]][index[1]]
  199. # get best values according to LCV
  200. for i in domains[index[0]][index[1]]:
  201. rating = lcv(domains, index, i)
  202. if (rating <= bestrating):
  203. bestrating = rating
  204. val = i
  205. return (index, val)
  206. # recursive solver that uses heuristics to decide what node to explore
  207. def solveh(working, domains, unassigned):
  208. if (not unassigned):
  209. return working
  210. # while there are unassigned values keep trying
  211. while(unassigned):
  212. # get next value using heuristics, remove this node from assigned
  213. nextThing = genVal(domains, working, unassigned)
  214. index = nextThing[0]
  215. val = nextThing[1]
  216. working[index[0]][index[1]] = val
  217. unassigned.remove(index)
  218. # check for invalidated nodes (empty domain)
  219. flag = True
  220. result = False
  221. newdomains = infer(domains, working, index[0], index[1], val)
  222. for i in range(0, 9):
  223. for j in range(0, 9):
  224. if (not domains[i][j]):
  225. flag = False
  226. # success! recurse
  227. if (flag): result = solveh(working, newdomains, copy.deepcopy(unassigned))
  228. if (result):
  229. return result
  230. elif (len(domains[index[0]][index[1]]) > 1): # remove from domain, keep going
  231. working[index[0]][index[1]] = 0
  232. domains[index[0]][index[1]].remove(val)
  233. unassigned.append(index)
  234. else: # no values worked :( return false
  235. return False
  236. # forward checking solver with heuristics
  237. def heuristic(start):
  238. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  239. domains = gen2Domains(start)
  240. # unassigned will be a list of positions we have to fill
  241. unassigned = []
  242. for i in range(0, 9):
  243. for j in range(0, 9):
  244. if (len(domains[i][j]) == 9):
  245. unassigned.append((i, j))
  246. # initial inferences
  247. for i in range(0, 9):
  248. for j in range(0, 9):
  249. if (working[i][j] != 0):
  250. domains = infer(domains, working, i, j, working[i][j])
  251. return solveh(working, domains, unassigned)
  252. def main():
  253. print("###########")
  254. print(*board, sep='\n')
  255. print("##########")
  256. if (algotype == str(0)):
  257. result = naive(board)
  258. elif (algotype == str(1)):
  259. result = forward(board)
  260. elif (algotype == str(2)):
  261. result = heuristic(board)
  262. else:
  263. print("No valid algorithm selected. RIP.")
  264. print("###########")
  265. print(*result, sep='\n')
  266. print("##########")
  267. main()