sudoku.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 False
  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 False
  80. return (working, 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. return solve(working, domains, unassigned, 0)
  143. # returns size of domain for a given index
  144. def domsize(domains, index):
  145. return (len(domains[index[0]][index[1]]))
  146. # returns the # of 0s that are in the same row, col, or box as index
  147. def related(brd, index):
  148. count = 0
  149. # count 0s in row + col
  150. for i in range(0, 9):
  151. if (brd[index[0]][i] == 0 and i != index[1]):
  152. ++count
  153. if (brd[i][index[1]] == 0 and i != index[0]):
  154. ++count
  155. # count for "box" as well
  156. rownum = int(index[0] / 3)
  157. colnum = int(index[1] / 3)
  158. for i in range(rownum * 3, rownum * 3 + 3):
  159. for j in range(colnum * 3, colnum * 3 + 3):
  160. if (brd[i][j] == 0 and (i != index[0] and j != index[1])):
  161. ++count
  162. return count
  163. # returns the # of constraints that will follow from assigning index with val
  164. def lcv(solutions, index, val):
  165. count = 0
  166. # count 0s in row + col
  167. for i in range(0, 9):
  168. if (val in solutions[index[0]][i] and i != index[1]):
  169. ++count
  170. if (val in solutions[i][index[1]] and i != index[0]):
  171. ++count
  172. # count for "box" as well
  173. rownum = int(index[0] / 3)
  174. colnum = int(index[1] / 3)
  175. for i in range(rownum * 3, rownum * 3 + 3):
  176. for j in range(colnum * 3, colnum * 3 + 3):
  177. if (val in solutions[i][j] and (i != index[0] and j != index[1])):
  178. ++count
  179. return count
  180. # return the correct node + val to try
  181. def genVal(domains, working, unassigned):
  182. # used to track intermediary values
  183. heap = []
  184. superheap = []
  185. bestrating = 1.0
  186. # get the best indices according to domain size
  187. for i in unassigned:
  188. rating = domsize(domains, i) / 9.0
  189. if (rating < bestrating):
  190. bestrating = rating
  191. heap = [i]
  192. elif (rating == bestrating):
  193. heap.append(i)
  194. # get the best indices according to degree(related cells)
  195. bestrating = 1
  196. for i in heap:
  197. rating = related(working, i) / 27.0
  198. if (rating < bestrating):
  199. bestrating = rating
  200. superheap = [i]
  201. elif (rating == bestrating):
  202. superheap.append(i)
  203. index = superheap[0]
  204. bestrating = 27
  205. val = working[index[0]][index[1]]
  206. # get best values according to LCV
  207. for i in domains[index[0]][index[1]]:
  208. rating = lcv(domains, index, i)
  209. if (rating <= bestrating):
  210. bestrating = rating
  211. val = i
  212. return (index, val)
  213. # recursive solver that uses heuristics to decide what node to explore
  214. def solveh(working, domains, unassigned, count):
  215. if (not unassigned):
  216. return (working, count)
  217. # while there are unassigned values keep trying
  218. while(unassigned):
  219. # get next value using heuristics, remove this node from assigned
  220. nextThing = genVal(domains, working, unassigned)
  221. index = nextThing[0]
  222. val = nextThing[1]
  223. working[index[0]][index[1]] = val
  224. unassigned.remove(index)
  225. # check for invalidated nodes (empty domain)
  226. flag = True
  227. result = False
  228. newdomains = infer(domains, working, index[0], index[1], val)
  229. for i in range(0, 9):
  230. for j in range(0, 9):
  231. if (not domains[i][j]):
  232. flag = False
  233. count += 1
  234. # took too long
  235. if (count >= 10000):
  236. print("took too long")
  237. return False
  238. # success! recurse
  239. if (flag): result = solveh(working, newdomains, copy.deepcopy(unassigned), count)
  240. if (result):
  241. return result
  242. elif (len(domains[index[0]][index[1]]) > 1): # remove from domain, keep going
  243. working[index[0]][index[1]] = 0
  244. domains[index[0]][index[1]].remove(val)
  245. unassigned.append(index)
  246. else: # no values worked :( return false
  247. return False
  248. # forward checking solver with heuristics
  249. def heuristic(start):
  250. working = copy.deepcopy(start) # this is only "filled in values" and 0s
  251. domains = gen2Domains(start)
  252. # unassigned will be a list of positions we have to fill
  253. unassigned = []
  254. for i in range(0, 9):
  255. for j in range(0, 9):
  256. if (len(domains[i][j]) == 9):
  257. unassigned.append((i, j))
  258. # initial inferences
  259. for i in range(0, 9):
  260. for j in range(0, 9):
  261. if (working[i][j] != 0):
  262. domains = infer(domains, working, i, j, working[i][j])
  263. return solveh(working, domains, unassigned, 0)
  264. def main():
  265. averages = []
  266. bverages = []
  267. cverages = []
  268. for i in range(0, 72):
  269. avgA = 0
  270. avgB = 0
  271. avgC = 0
  272. for j in range(1, 11):
  273. filepath = "sudoku_problems/" + i + "/" + j + ".sd"
  274. # import board
  275. with open(filepath) as file:
  276. board = file.read().splitlines()
  277. board = board[:-1]
  278. # convert to list of list of ints
  279. for l in board:
  280. board[board.index(l)] = list(map(lambda x: int(x), l.split()))
  281. avgA += naive(board)
  282. avgB += forward(board)
  283. avgC += heuristic(board)
  284. averages.append(avgA / 10.0)
  285. bverages.append(avgB / 10.0)
  286. cverages.append(avgC / 10.0)
  287. figure, axes = plt.subplots(1, 1, True)
  288. axes.plot(range(1, 72), averages, label='Naive Algorithm')
  289. axes.plot(range(1, 72), bverages, label='Forward-Checking Algorithm')
  290. axes.plot(range(1, 72), cverages, label='Heuristics')
  291. axes.legend()
  292. plt.xlabel("Number of Initial Valued Filled In")
  293. plt.ylabel("Average Number of Variable Assignments in 10 Runs")
  294. plt.savefig("graph.pdf")
  295. main()