sudoku.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import copy
  2. from contextlib import suppress
  3. from heapq import heappush, heappop
  4. import matplotlib.pyplot as plt
  5. # return a board that is like the board b, but has domains for each element of b (always 1-9)
  6. def genDomains(b):
  7. for row in range(0, 9):
  8. for cell in range(0, 9):
  9. if (b[row][cell] == 0):
  10. b[row][cell] = list(range(1, 10))
  11. return b
  12. # returns True if value is valid
  13. def valid(brd, row, col, val):
  14. # check row
  15. if (val in brd[row]):
  16. return False
  17. # check column
  18. for i in range(0, 9):
  19. if (brd[i][col] == val):
  20. return False
  21. # check "box"
  22. rownum = int(row / 3)
  23. colnum = int(col / 3)
  24. for i in range(rownum * 3, rownum * 3 + 3):
  25. for j in range(colnum * 3, colnum * 3 + 3):
  26. if (brd[i][j] == val):
  27. return False
  28. return True
  29. # naive backtracking solver
  30. def naive(start):
  31. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  32. solution = genDomains(start)
  33. # unassigned will be a list of positions we have to fill
  34. unassigned = []
  35. for i in range(0, 9):
  36. for j in range(0, 9):
  37. if (isinstance(solution[i][j], list)):
  38. unassigned.append((i, j))
  39. assumptions = []
  40. if(len(unassigned) == 0):
  41. return (working, 0)
  42. # count assignments
  43. count = 0
  44. # while there are unassigned vars, keep going
  45. while(len(unassigned)):
  46. index = unassigned[-1]
  47. success = False
  48. # iterate over all values in the domain list
  49. while solution[index[0]][index[1]]:
  50. i = solution[index[0]][index[1]].pop()
  51. count += 1
  52. # took too long
  53. if (count >= 10000):
  54. print("took too long")
  55. return 10000
  56. # check if this part of the domain(solution) is valid
  57. if (valid(working, index[0], index[1], i)):
  58. #count += 1
  59. #if (count >= 10000):
  60. # print("took too long")
  61. # return False
  62. solution[index[0]][index[1]].append(i) # keep in the domain
  63. working[index[0]][index[1]] = i
  64. assumptions.append(index)
  65. unassigned.pop()
  66. success = True
  67. break
  68. if (success):
  69. continue
  70. else:
  71. # restore domain to full since we failed
  72. solution[index[0]][index[1]] = list(range(1, 10))
  73. working[index[0]][index[1]] = 0
  74. lastdex = assumptions.pop()
  75. solution[lastdex[0]][lastdex[1]].remove(working[lastdex[0]][lastdex[1]])
  76. working[lastdex[0]][lastdex[1]] = 0
  77. unassigned.append(lastdex)
  78. # if we exit without assigning everything, we should have failed
  79. if (unassigned): return 10000
  80. return count
  81. # returns a board (domains) where inferences are made for the cell at row, col
  82. def infer(solutions, brd, row, col, val):
  83. domains = copy.deepcopy(solutions)
  84. # remove from same row & col
  85. for i in range(0, 9):
  86. if (val in domains[row][i] and i != col):
  87. domains[row][i].remove(val)
  88. if (val in domains[i][col] and i != row):
  89. domains[i][col].remove(val)
  90. # remove for "box"
  91. rownum = int(row / 3)
  92. colnum = int(col / 3)
  93. for i in range(rownum * 3, rownum * 3 + 3):
  94. for j in range(colnum * 3, colnum * 3 + 3):
  95. if (val in domains[i][j] and (i != row and j != col)):
  96. domains[i][j].remove(val)
  97. return domains
  98. # generates domains in a format supporting forward checking
  99. def gen2Domains(b):
  100. for row in range(0, 9):
  101. for cell in range(0, 9):
  102. if (b[row][cell] == 0):
  103. b[row][cell] = list(range(1, 10))
  104. else:
  105. b[row][cell] = [b[row][cell]]
  106. return b
  107. # recursive solver for forward-checking
  108. def solve(working, domains, unassigned, count):
  109. if (not unassigned):
  110. return (working, count)
  111. index = unassigned.pop()
  112. # for every value in the domain, check if using it works. if all fail, backtrack.
  113. for i in domains[index[0]][index[1]]:
  114. working[index[0]][index[1]] = i
  115. newdomains = infer(domains, working, index[0], index[1], i)
  116. count += 1
  117. # took too long
  118. if (count >= 10000):
  119. print("took too long")
  120. return False
  121. result = solve(working, newdomains, copy.deepcopy(unassigned), count)
  122. if (result):
  123. return result
  124. else:
  125. continue
  126. return False
  127. # forward checking solver
  128. def forward(start):
  129. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  130. domains = gen2Domains(start)
  131. # unassigned will be a list of positions we have to fill
  132. unassigned = []
  133. for i in range(0, 9):
  134. for j in range(0, 9):
  135. if (len(domains[i][j]) == 9):
  136. unassigned.append((i, j))
  137. # forward-checking on pre-assigned values
  138. for i in range(0, 9):
  139. for j in range(0, 9):
  140. if (working[i][j] != 0):
  141. domains = infer(domains, working, i, j, working[i][j])
  142. result = solve(working, domains, unassigned, 0)
  143. if (result): return result[1]
  144. else: return 10000
  145. # returns size of domain for a given index
  146. def domsize(domains, index):
  147. return (len(domains[index[0]][index[1]]))
  148. # returns the # of 0s that are in the same row, col, or box as index
  149. def related(brd, index):
  150. count = 0
  151. # count 0s in row + col
  152. for i in range(0, 9):
  153. if (brd[index[0]][i] == 0 and i != index[1]):
  154. ++count
  155. if (brd[i][index[1]] == 0 and i != index[0]):
  156. ++count
  157. # count for "box" as well
  158. rownum = int(index[0] / 3)
  159. colnum = int(index[1] / 3)
  160. for i in range(rownum * 3, rownum * 3 + 3):
  161. for j in range(colnum * 3, colnum * 3 + 3):
  162. if (brd[i][j] == 0 and (i != index[0] and j != index[1])):
  163. ++count
  164. return count
  165. # returns the # of constraints that will follow from assigning index with val
  166. def lcv(solutions, index, val):
  167. count = 0
  168. # count 0s in row + col
  169. for i in range(0, 9):
  170. if (val in solutions[index[0]][i] and i != index[1]):
  171. ++count
  172. if (val in solutions[i][index[1]] and i != index[0]):
  173. ++count
  174. # count for "box" as well
  175. rownum = int(index[0] / 3)
  176. colnum = int(index[1] / 3)
  177. for i in range(rownum * 3, rownum * 3 + 3):
  178. for j in range(colnum * 3, colnum * 3 + 3):
  179. if (val in solutions[i][j] and (i != index[0] and j != index[1])):
  180. ++count
  181. return count
  182. # return the correct node + val to try
  183. def genVal(domains, working, unassigned):
  184. # used to track intermediary values
  185. heap = []
  186. superheap = []
  187. bestrating = 1.0
  188. # get the best indices according to domain size
  189. for i in unassigned:
  190. rating = domsize(domains, i) / 9.0
  191. if (rating < bestrating):
  192. bestrating = rating
  193. heap = [i]
  194. elif (rating == bestrating):
  195. heap.append(i)
  196. # get the best indices according to degree(related cells)
  197. bestrating = 1
  198. for i in heap:
  199. rating = related(working, i) / 27.0
  200. if (rating < bestrating):
  201. bestrating = rating
  202. superheap = [i]
  203. elif (rating == bestrating):
  204. superheap.append(i)
  205. index = superheap[0]
  206. bestrating = 27
  207. val = working[index[0]][index[1]]
  208. # get best values according to LCV
  209. for i in domains[index[0]][index[1]]:
  210. rating = lcv(domains, index, i)
  211. if (rating <= bestrating):
  212. bestrating = rating
  213. val = i
  214. return (index, val)
  215. # recursive solver that uses heuristics to decide what node to explore
  216. def solveh(working, domains, unassigned, count):
  217. if (not unassigned):
  218. return (working, count)
  219. # while there are unassigned values keep trying
  220. while(unassigned):
  221. # get next value using heuristics, remove this node from assigned
  222. nextThing = genVal(domains, working, unassigned)
  223. index = nextThing[0]
  224. val = nextThing[1]
  225. working[index[0]][index[1]] = val
  226. unassigned.remove(index)
  227. # check for invalidated nodes (empty domain)
  228. flag = True
  229. result = False
  230. newdomains = infer(domains, working, index[0], index[1], val)
  231. for i in range(0, 9):
  232. for j in range(0, 9):
  233. if (not domains[i][j]):
  234. flag = False
  235. count += 1
  236. # took too long
  237. if (count >= 10000):
  238. print("took too long")
  239. return False
  240. # success! recurse
  241. if (flag): result = solveh(working, newdomains, copy.deepcopy(unassigned), count)
  242. if (result):
  243. return result
  244. elif (len(domains[index[0]][index[1]]) > 1): # remove from domain, keep going
  245. working[index[0]][index[1]] = 0
  246. domains[index[0]][index[1]].remove(val)
  247. unassigned.append(index)
  248. else: # no values worked :( return false
  249. return False
  250. # forward checking solver with heuristics
  251. def heuristic(start):
  252. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  253. domains = gen2Domains(start)
  254. # unassigned will be a list of positions we have to fill
  255. unassigned = []
  256. for i in range(0, 9):
  257. for j in range(0, 9):
  258. if (len(domains[i][j]) == 9):
  259. unassigned.append((i, j))
  260. # initial inferences
  261. for i in range(0, 9):
  262. for j in range(0, 9):
  263. if (working[i][j] != 0):
  264. domains = infer(domains, working, i, j, working[i][j])
  265. result = solveh(working, domains, unassigned, 0)
  266. if (result): return result[1]
  267. else: return 10000
  268. def main():
  269. plt.ioff()
  270. plt.switch_backend('agg')
  271. averages = []
  272. bverages = []
  273. cverages = []
  274. for i in range(1, 72):
  275. avgA = 0
  276. avgB = 0
  277. avgC = 0
  278. for j in range(1, 11):
  279. filepath = "sudoku_problems/" + str(i) + "/" + str(j) + ".sd"
  280. # import board
  281. with open(filepath) as file:
  282. board = file.read().splitlines()
  283. board = board[:-1]
  284. # convert to list of list of ints
  285. for l in board:
  286. board[board.index(l)] = list(map(lambda x: int(x), l.split()))
  287. avgA += naive(board)
  288. avgB += forward(board)
  289. avgC += heuristic(board)
  290. averages.append(avgA / 10.0)
  291. bverages.append(avgB / 10.0)
  292. cverages.append(avgC / 10.0)
  293. figure, axes = plt.subplots(1, 1, True)
  294. axes.plot(range(1, 72), averages, label='Naive Algorithm')
  295. axes.plot(range(1, 72), bverages, label='Forward-Checking Algorithm')
  296. axes.plot(range(1, 72), cverages, label='Heuristics')
  297. axes.legend()
  298. plt.xlabel("Number of Initial Valued Filled In")
  299. plt.ylabel("Average Number of Variable Assignments in 10 Runs")
  300. plt.savefig("graph.pdf")
  301. main()