I discovered Ruby this week. I was amazed at how easy it was to program
in it without a book or any real manual.
I've written the following program. It looks too much like the python
original to be good idiomatic ruby. I'd appreciate suggestions how to
improve it.
Thanks.
Logesh
#returns the ways one can place n queens on a
#chessboard of size n*n so that no queen is attacking another
#Ruby 1.8.3; 15 June 2006
def nqueens
$n = 8
$board = [nil] * ($n+1)
def choose(k)
if k > $n
print $board, "\n"
else
for i in 1..$n
$board[k] = i
choose(k + 1) if k == 1 or stillgood(k)
end
end
end
def stillgood(k)
for i in 1...k
return false if ($board[k] == $board[i]) or
(k-i == ($board[k] - $board[i]).abs)
end
return true
end
end
nqueens.choose(1)