Sudoku: Difference between revisions

Content added Content deleted
(add Ruby)
Line 600:
=={{header|Ruby}}==
Example of a back-tracking solver, from [[wp:Algorithmics of sudoku]]
{{works with|Ruby|1.8.7+}}
<lang ruby>def read_matrix(fh)
matrix = []
Line 652 ⟶ 653:
def solve_sudoku(matrix)
whileloop truedo
options = []
(0..8).each { |i|
Line 659 ⟶ 660:
p = permissible(matrix, i, j)
# If nothing is permissible, there is no solution at this level.
return falsenil if (p.length == 0)
options.push({:i => i, :j => j, :permissible => p})
}
Line 666 ⟶ 667:
return matrix if options.length == 0
omin = options.minmin_by { |x| a,x[:permissible].length b |}
a[:permissible].length <=> b[:permissible].length
}
# If there is an option with only one solution, set it and re-check permissibility
Line 681 ⟶ 680:
mtmp[omin[:i]][omin[:j]] = v
ret = solve_sudoku(mtmp)
ifreturn ret !=if falseret
return ret
end
}
# We did an exhaustive search on this branch and nothing worked out.
return falsenil
end
end
def print_matrix(matrix)
if (not matrix == false)
printputs "Impossible\n"
return
end