8クイーン問題をRubyで解こうとしたが、うまくいかない。なぜだ?
疲れたのであとで考える。
#!/usr/bin/ruby -Ks # # 8 queen problem $n = 8 $ini_row = 1 class Queen def initialize(col, neighbor) @row = $ini_row @col = col @neighbor = neighbor end def show print " "*(@row-1), "Q", " "*($n+2-@row), "#@row, #@col\n" end def findSolution while @neighbor and @neighbor.canAttack(@row, @col) unless advance return false end end true end def canAttack(row, col) if (row == @row) or ((@col-col).abs == (@row-row).abs) return true end @neighbor and @neighbor.canAttack(row, col) end def advance if @row < $n @row += 1 return findSolution end if @neighbor and (not @neighbor.advance) return false end @row = 1 return findSolution end end lastQueen = nil (1..$n).each do |i| lastQueen = Queen.new(i, lastQueen) lastQueen.findSolution lastQueen.show end