sorting tournament seeds

前端 未结 6 1250
夕颜
夕颜 2021-02-09 17:40

I\'m making a HTML/JS powered single/double elimination bracket web app. I am struggling to figure out how to assign the first round matches from a list of seeded teams/players.

6条回答
  •  面向向阳花
    2021-02-09 18:30

    I was really intrigued and impressed with Cliff's algorithm here. I think it is very clever. Here is a simple implementation I wrote in ruby. The BYEs are returned as -1.

    def seed(n)
      rounded_n = next_power_of_two(n)
      nbr_bits_required=rounded_n.to_s(2).length-1
      binary_seeds = Array.new(rounded_n) {Array.new(nbr_bits_required)}
      binary_seeds[0]=Array.new(nbr_bits_required){0}
    
      nbr_bits_required.times do |col|    
        1.upto(rounded_n-1) do |row|
          if row % (2**(col+1)) == 0
            #asterisk in the previous row, don't inverse the bit
            binary_seeds[row][col] = binary_seeds[row-1][col]
          else
            #no asterisk in the previous row, inverse the bit
            binary_seeds[row][col] = binary_seeds[row-1][col] == 0 ? 1 : 0
          end
        end
      end
    
      #output the result in decimal format
      binary_seeds.collect {|bs| s=(bs.join("")).to_i(2)+1; s>n ? -1 : s}
    end
    
    def next_power_of_two(n)
      k = 1
      k*=2 while k

    Test it out:

    seed(8)
    => [1, 8, 5, 4, 3, 6, 7, 2]
    
    seed(6)
    => [1, -1, 5, 4, 3, 6, -1, 2]
    

提交回复
热议问题