Created
November 19, 2019 08:31
-
-
Save rugyoga/bb3a8c559a57469f3bd92c71be05ebbf to your computer and use it in GitHub Desktop.
Short ruby solution to N Queens analogous to my Elixir solution
This file contains hidden or 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 props(f, r) | |
[f, f + r, f - r] | |
end | |
def safe?(queens, f, r) | |
p_props = props(f, r) | |
queens.all? { |q| p_props.zip(props(*q)).all?{ |p| p[0] != p[1] } } | |
end | |
def solve(n, queens, rank, &block) | |
if rank == n | |
yield queens | |
else | |
n.times do |file| | |
if safe?(queens, file, rank) | |
queens << [file, rank] | |
solve(n, queens, rank + 1, &block) | |
queens.pop | |
end | |
end | |
end | |
end | |
solve(ARGV[0].to_i, [], 0) { |solution| puts solution.inspect } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment