ruby-listで…(3)

結局、最初の方針であってた。

class GameMC
  def initialize arr
    set_seed(arr)
    @game_size = arr.length/2
    @count = 0
    shuffle
  end
  
  def set_seed a
    @seed=[]
    a.each_with_index do |e,i|
      a[i+1..-1].each {|ele| @seed << [e, ele]}
    end
  end

  def ok? result
    begin
      result.each_with_index do |e,i|
        result[i+1..-1].each {|ele| return false unless (e & ele).empty?}
      end
      return true
    rescue #nilの時に例外が発生するのでそれを補則する。
      return true
    end
  end

  def generate_combination
    result = []
    until result.size == @game_size
      @count += 1
      return result if @count >= 100
      result << random_select
      @seed << result.pop unless ok? result
    end
    result
  end
  
  def shuffle
    @seed.each_index do |i|
      j=rand(i+1)
      @seed[i],@seed[j] = @seed[j], @seed[i]
    end
  end
  
  def random_select
    tmp = @seed.shift
  end
          
  def game
    unless @seed.empty?
      @count=0
      @used_numbers = []
      p generate_combination
    else
      puts "No Combination!"
    end
  end
end
n=6
g=GameMC.new((1..n).to_a)
10.times{|e| g.game}

# ##実行結果##
# [[5, 6], [1, 3], [2, 4]]
# [[1, 4], [3, 5], [2, 6]]
# [[1, 2], [4, 6]]
# [[1, 6], [3, 4], [2, 5]]
# [[3, 6], [1, 5]]
# [[4, 5], [2, 3], nil]
# No Combination!
# No Combination!
# No Combination!
# No Combination!
#

渡す配列が名前でも大丈夫。