Sudoku!
This is such a classic problem in code. And I got in the puzzle-solving mood this afternoon after determining that the old "how many ways can a robot climb n stairs if he can take 1 or 2 steps at a time" is actually fibonacci(n) !
Anyway, so here's my sudoku, in ruby, of course. ;o)
def valid(num, x, y, solution)
return false if (solution[y].include?(num))
return false if (solution.map{|row|row[x]}.include?(num))
(x-x%3).upto(x-x%3+2) { |tmpX|
(y-y%3).upto(y-y%3+2) { |tmpY|
return false if (solution[tmpY][tmpX] == num)
}
}
return true
end
def solve(grid, pos=0, solution=grid.clone)
return solution if (pos == 80)
return solve(grid, pos+1, solution) if (solution[pos/9][pos%9] > 0)
(1..9).select{|num| valid(num, pos%9, pos/9, solution)}.each{|num|
solution[pos/9][pos%9] = num
return solution if solve(grid, pos+1, solution)
}
solution[pos/9][pos%9] = 0
return false
end
# Example usage and printout
grid = [
[9,0,0,0,0,0,7,3,1],
[6,3,1,8,7,5,0,2,0],
[0,0,7,0,0,0,6,0,0],
[0,0,0,3,4,7,0,1,0],
[0,0,4,0,0,0,3,0,0],
[0,1,0,9,8,6,0,0,0],
[0,0,6,0,0,0,9,0,0],
[0,4,0,7,9,8,1,6,5],
[1,8,9,0,0,0,0,0,3]
]
solution = solve(grid)
puts solution.map{|row|row.join(",")}.join("\n")