Last active
September 29, 2015 01:20
-
-
Save ryandgoldenberg1/1c8a9c882c7c4f18f629 to your computer and use it in GitHub Desktop.
Eight Queens Problem
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
class EightQueens | |
def initialize | |
@workset = (0...64).map { |i| [i] } | |
end | |
def queen_attacks(pos) | |
(horizontal_attacks(pos) + | |
vertical_attacks(pos) + | |
main_diagonal_attacks(pos) + | |
secondary_diagonal_attacks(pos)).uniq | |
end | |
def horizontal_attacks(pos) | |
(0...8).map { |i| (pos / 8 * 8) + i } | |
end | |
def vertical_attacks(pos) | |
(0...8).map { |i| (pos % 8) + i * 8 } | |
end | |
def main_diagonal_attacks(pos) | |
(0...8).map {|i| i * 9 + (pos / 8 - pos % 8) * 8}.select {|i| i >= 0 && i < 64} | |
end | |
def secondary_diagonal_attacks(pos) | |
(0...8).map {|i| 7 * (i + 1) + (pos / 8 - (8 - pos % 8) + 1) * 8}.select {|i| i >= 0 && i < 64} | |
end | |
def safe_squares(queens) | |
squares = (0...64).to_a | |
queens.each do |queen| | |
squares -= (queen_attacks(queen) + [queen]) | |
end | |
squares | |
end | |
def solve | |
while @workset.length > 0 | |
queens = @workset.pop | |
return queens if queens.length == 8 | |
safe_squares(queens).each do |square| | |
@workset << (queens + [square]) | |
end | |
end | |
end | |
end | |
puts EightQueens.new.solve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment