Created
August 7, 2011 02:37
-
-
Save stevez/1129998 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SudokuSolver | |
def initialize(puzzle) | |
@@p = puzzle.split(//) | |
end | |
#Algorithm to solve the sudoku puzzle | |
def solver | |
#81 times for each block in the puzzle | |
81.times do |j| | |
next if @@p[j].to_i!=0 | |
candidatesArray = getCandidates(j) | |
candidatesArray.each do |v| | |
@@p[j]=v.to_s | |
foundAll = solver | |
if(foundAll == true) | |
return true | |
end | |
end | |
# finished trying all the candidates, backtrack | |
@@p[j]=0 | |
return false | |
end | |
return true | |
end | |
def getCandidates(j) | |
Array array = [1,2,3,4,5,6,7,8,9] | |
row = j/9 *9 | |
col = j%9 | |
#find the cells with the same row | |
9.times do |k| | |
m = @@p[row+k].to_i | |
if(m) | |
array.delete(m) | |
end | |
end | |
#find the cells in the same column | |
9.times do |k| | |
m = @@p[k*9 + col].to_i | |
if(m) | |
array.delete(m) | |
end | |
end | |
#find the cells in the same sub cube | |
start_row = j/27 * 3 | |
start_col = j%9/3 * 3 | |
3.times do |t| | |
3.times do |l| | |
m = @@p[(start_row + t)*9 + start_col + l].to_i | |
if(m) | |
array.delete(m) | |
end | |
end | |
end | |
return array | |
end | |
def printResult | |
puts "\n\nThe Solution is:\n" | |
print "+-----------------------------+\n|" | |
1.upto(81) do |x| | |
print " #{@@p[x-1]} " | |
if x%3==0 and x%9 !=0 | |
print "|" | |
end | |
if x%9==0 and x%81 !=0 | |
print"|\n|-----------------------------|\n|" | |
end | |
if x%81==0 | |
puts "|" | |
end | |
end | |
puts "+-----------------------------+" | |
end | |
end | |
question = "000700390090500000300240800700900200000000000003007008004026007000005060026001000" | |
answer = SudokuSolver.new(question) | |
puts "\n\n\nSolving puzzle, wait one moment..." | |
answer.solver | |
answer.printResult |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment