Created
July 8, 2012 23:10
-
-
Save lachie/3073377 to your computer and use it in GitHub Desktop.
Luke's 8 queens, edited for style ;)
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
# Check last queen for conflict | |
def conflict(p) | |
i_last = p.length-1 | |
(0..i_last-1).any? {|i| | |
p[i] == p[-1] || # conflict on col | |
i-p[i] == i_last-p[i_last] || # conflict on diag | |
i+p[i] == i_last+p[i_last] # conflict on other diag | |
} | |
end | |
# Recursively solve for solutions starting with sol | |
def solve(sol) | |
case | |
when conflict(sol) | |
[] | |
when sol.length >= 8 # A solution! | |
[sol.dup] | |
else | |
(1..8).map{|p| solve(sol + [p]) }.flatten(1) # The magic of map-flatten | |
end | |
end | |
puts solve([1]).inspect # Find all solutions with a queen in the corner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment