Sha256: 79c9adabd09d0e121569295c14bc59a5b59d4703d3897caf705c20ff348a76f6

Contents?: true

Size: 1.67 KB

Versions: 35

Compression:

Stored size: 1.67 KB

Contents

# encoding: utf-8

# SimpleTournament
class SimpleTournament
  attr_reader :tournament, :number, :matches

  # initialize tournament by number
  def initialize(number)
    @number = number
    @matches = []
    cnt = 0
    @tournament = []
    while number >= (2**cnt)
      tournament << Array.new(2**cnt)
      cnt += 1
    end
    diff = number - (2**(cnt - 1))
    @tournament << Array.new(diff * 2) unless (diff == 0)
  end

  # apply challengers to tournament
  def apply_challengers(challengers)
    fail 'incorrect challengers size. challengers must equals tournament.size' unless challengers.size == @number
    @tournament.reverse_each do |outer|
      outer.each_with_index do |v, i|
        poped = challengers.pop
        return @tournament if poped.nil?
        outer[i] = poped
      end
    end
  end

  # start tournament match. set result to tournament, matches
  def start_match(proc)
    @tournament.reverse_each.with_index do |outer, outer_index|
      outer.reverse_each.with_index do |inner, inner_index|
        next if inner_index.odd?
        next if inner_index == outer.size - 1
        rets = proc.call outer[-(inner_index + 1)], outer[-(inner_index + 2)], outer_index
        winner = rets.first
        @matches << rets.last
        set_winner(winner, outer_index)
      end
    end
  end

  private

  def set_winner(winner, outer_index)
    @tournament[0..-(outer_index + 1)].reverse_each do |replace_outer|
      replace_outer.reverse_each.with_index do |reverse_inner, reverse_inner_index|
        next unless reverse_inner.nil?
        return replace_outer[-(reverse_inner_index + 1)] = winner
      end
    end
  end
end

Version data entries

35 entries across 35 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.151 lib/simple_tournament.rb
tbpgr_utils-0.0.150 lib/simple_tournament.rb
tbpgr_utils-0.0.149 lib/simple_tournament.rb
tbpgr_utils-0.0.148 lib/simple_tournament.rb
tbpgr_utils-0.0.147 lib/simple_tournament.rb
tbpgr_utils-0.0.146 lib/simple_tournament.rb
tbpgr_utils-0.0.145 lib/simple_tournament.rb
tbpgr_utils-0.0.144 lib/simple_tournament.rb
tbpgr_utils-0.0.143 lib/simple_tournament.rb
tbpgr_utils-0.0.142 lib/simple_tournament.rb
tbpgr_utils-0.0.141 lib/simple_tournament.rb
tbpgr_utils-0.0.140 lib/simple_tournament.rb
tbpgr_utils-0.0.139 lib/simple_tournament.rb
tbpgr_utils-0.0.138 lib/simple_tournament.rb
tbpgr_utils-0.0.137 lib/simple_tournament.rb
tbpgr_utils-0.0.136 lib/simple_tournament.rb
tbpgr_utils-0.0.135 lib/simple_tournament.rb
tbpgr_utils-0.0.134 lib/simple_tournament.rb
tbpgr_utils-0.0.133 lib/simple_tournament.rb
tbpgr_utils-0.0.132 lib/simple_tournament.rb