Created
October 22, 2011 03:42
-
-
Save shugo/1305574 to your computer and use it in GitHub Desktop.
solve the N queens problem using flat_map
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
require "pp" | |
def queens(n, k = n) | |
if k == 0 | |
[[]] | |
else | |
queens(n, k - 1).flat_map {|queens| | |
(1..n).map {|col| [k, col]}.select {|queen| | |
queens.all? {|q| | |
q[0] != queen[0] && | |
q[1] != queen[1] && | |
(q[0] - queen[0]).abs != (q[1] - queen[1]).abs | |
} | |
}.map {|queen| [queen, *queens]} | |
} | |
end | |
end | |
pp queens(8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment