Sha256: a85f276678f80dc47d5382f1ced96efa4da32b180645204bae561f1903cbb591

Contents?: true

Size: 1.63 KB

Versions: 41

Compression:

Stored size: 1.63 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

41 entries across 41 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.116 lib/simple_tournament.rb
tbpgr_utils-0.0.115 lib/simple_tournament.rb
tbpgr_utils-0.0.114 lib/simple_tournament.rb
tbpgr_utils-0.0.113 lib/simple_tournament.rb
tbpgr_utils-0.0.112 lib/simple_tournament.rb
tbpgr_utils-0.0.111 lib/simple_tournament.rb
tbpgr_utils-0.0.110 lib/simple_tournament.rb
tbpgr_utils-0.0.109 lib/simple_tournament.rb
tbpgr_utils-0.0.108 lib/simple_tournament.rb
tbpgr_utils-0.0.107 lib/simple_tournament.rb
tbpgr_utils-0.0.106 lib/simple_tournament.rb
tbpgr_utils-0.0.105 lib/simple_tournament.rb
tbpgr_utils-0.0.104 lib/simple_tournament.rb
tbpgr_utils-0.0.103 lib/simple_tournament.rb
tbpgr_utils-0.0.102 lib/simple_tournament.rb
tbpgr_utils-0.0.101 lib/simple_tournament.rb
tbpgr_utils-0.0.100 lib/simple_tournament.rb
tbpgr_utils-0.0.99 lib/simple_tournament.rb
tbpgr_utils-0.0.98 lib/simple_tournament.rb
tbpgr_utils-0.0.97 lib/simple_tournament.rb