Skip to content

Instantly share code, notes, and snippets.

@shugo
Created October 22, 2011 03:42
Show Gist options
  • Save shugo/1305574 to your computer and use it in GitHub Desktop.
Save shugo/1305574 to your computer and use it in GitHub Desktop.
solve the N queens problem using flat_map
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