Thursday, October 13, 2016

The "Eight Queens" problem solved in Ruby

Here is an interesting solution for the classic "Eight Queens" problem.

It is easy to learn that, in chess, a queen moves like this:


The "Eight Queens" problem consists of trying to place eight queens in a 8x8 chessboard, in such a manner that none of them may capture other queen.

After thinking a while, I solved the problem with this small program.



I'd like to call your attention to the fact I represented the chess board with a Hash, not as an 8x8 Array. And you may also notice that the keys in this Hash are arrays! Arrays with the coordinates of the position. The values are either 0, for an empty position, or 1 for an occupied position.

In my old Dell Vostro Duo Core I used the command

$ time ruby eightqueens.rb

to run this program and got the following time statistics:

ruby eightqueens.rb  0,62s user 0,10s system 49% cpu 1,453 total

Very fast, don't you think? I dare. I double dare someone to post a gist at GitHub with a faster solution!!! LOL

I'll be waiting! And I'll be back!!!