Saturday, January 16, 2010

アルゴリズム問題

http://www.itmedia.co.jp/enterprise/articles/0912/05/news002.html

class Board
  attr_accessor :cells
  attr_reader :width, :height
  def initialize(width, height)
    @width, @height = width + 2, height + 2
    @cells = Array.new(@height){ Array.new(@width){0} }
  end

  def place_peace
    2.upto(width-1) do |i|
      2.upto(height-1) do |j|
        cells[i][j] =
          (cells[i-2][j] == 0) && (cells[i][j-2] == 0) ? 1 : 0
      end
    end
  end

  def draw_board
    cells.each_with_index do |line, i|
            next if [0, 1].include?(i)
      line.each_with_index do |cell, j|
                next if [0, 1].include?(j)
                print cell == 1 ? "◎" : "+"
      end
            print "\n"
    end
  end
end


b = Board.new(10, 10)
b.place_peace
b.draw_board

No comments: