Skip to content

Instantly share code, notes, and snippets.

@lachie
Created July 8, 2012 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lachie/3073377 to your computer and use it in GitHub Desktop.
Save lachie/3073377 to your computer and use it in GitHub Desktop.
Luke's 8 queens, edited for style ;)
# 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