Created
January 3, 2010 14:13
-
-
Save marcric/267983 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
def safe?(col, others) | |
others.each_with_index do |c, r| | |
return false if col == c or (col - c).abs == (others.size - r).abs | |
end | |
end | |
def solve(n, solutions = [], cols=[]) | |
return solutions.push(cols) unless cols.size < n | |
n.times { |col| solve(n, solutions, cols + [col]) if safe?(col, cols) } | |
return solutions | |
end | |
def show_solutions(n) | |
solutions = solve(n) | |
puts "There are #{solutions.size} solutions for n = #{n}." | |
for cols in solutions | |
puts '', cols.map { |c| (0...n).map { |i| i == c ? '$ ' : '0 ' }.join } | |
end | |
end | |
show_solutions(6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment