-
-
Save MisterGlass/92a68bbaa9059b05ddfb to your computer and use it in GitHub Desktop.
Ruby implementation of a simple 8 queens solver
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
def checkSquare(c,r,b) | |
for i in b[c] do | |
if i == 1 | |
return false | |
end | |
end | |
for i in b do | |
if i[r] == 1 | |
return false | |
end | |
end | |
r2 = r | |
c2 = c | |
while r2 >=0 && c2 >= 0 do | |
if b[c2][r2] == 1 | |
return false | |
end | |
r2-=1 | |
c2-=1 | |
end | |
r2 = r | |
c2 = c | |
while r2 <= 7 && c2 >= 0 do | |
if b[c2][r2] == 1 | |
return false | |
end | |
r2+=1 | |
c2-=1 | |
end | |
r2 = r | |
c2 = c | |
while r2 >= 0 && c2 <= 7 do | |
if b[c2][r2] == 1 | |
return false | |
end | |
r2-=1 | |
c2+=1 | |
end | |
r2 = r | |
c2 = c | |
while r2 <= 7 && c2 <= 7 do | |
if b[c2][r2] == 1 | |
return false | |
end | |
r2+=1 | |
c2+=1 | |
end | |
return true | |
end | |
def cloneBoard(b) | |
b2 = Array.new(8) | |
for i in 0..7 | |
b2[i] = b[i].clone() | |
end | |
return b2 | |
end | |
#create a new array of 8 & pass a codeblock to populate it with new arrays | |
b = Array.new(8) { |i| Array.new(8, 0) } | |
c = 0 | |
r = 0 | |
s = Array.new() | |
while c >= 0 do | |
if checkSquare(c,r,b) then | |
b[c][r] = 1 | |
if c < 7 then | |
c+=1 | |
r=0 | |
else | |
s.push(cloneBoard(b)) | |
b[c][r] = 0 | |
begin | |
c-=1 | |
if c<0 then | |
break | |
end | |
r = b[c].index(1) | |
b[c][r] = 0 | |
r+=1 | |
end while r>7 | |
end | |
else | |
if r < 7 then | |
r+=1 # try next row | |
else | |
#move back a column | |
begin | |
c-=1 | |
if c<0 then | |
break | |
end | |
r = b[c].index(1) | |
b[c][r] = 0 | |
r+=1 | |
end while r>7 | |
end | |
end | |
end | |
for i in s | |
for c in i | |
for r in c | |
print r | |
end | |
puts() | |
end | |
puts('------------------') | |
end | |
puts("Total of #{s.length} solutions found") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment