From: Pete Yandell Date: 2006-06-16T10:47:13+09:00 Subject: Re: Newbie program Just for another data point, here's a version that I wrote ages ago that attempts to be as Ruby-ish as possible. The board is stored in such a way that a single line of Ruby can test if a new queen can be placed in a given square, and solutions are yielded to a block as they're found. (Put a 'break' into the block if you only want the first solution.) Pete Yandell http://9cays.com module Queens Queen = Struct.new(:x, :y) class Board < Array def to_s map {|q| "."*q.x + "X" + "."*(size-q.x-1)}.join("\n") + "\n" end def add(*q) Board.new(self + q) end end def self.solve(size = 8, queens = Board.new, &block) if queens.size == size yield queens else y = queens.size for x in 0...size unless queens.any? {|q| x == q.x or (x-q.x).abs == (y- q.y).abs } solve(size, queens.add(Queen.new(x,y)), &block) end end end end end Queens::solve {|q| print q.to_s, "\n" }