From: Daniel Finnie Date: 2006-12-11T06:09:07+09:00 Subject: Re: [QUIZ] Tournament Matchups (#105) --Boundary_(ID_7mMBSYuPFLAZYI71WIEG/w) Content-type: text/plain; charset=ISO-8859-1; format=flowed Content-transfer-encoding: 7BIT Following (and attached) is the copy of my code. The main logic of it is very simple: 1. Create "bye" teams until there is a power of two 2. From an array sorted by "goodness" of a team, make matches by taking a team from the two ends. A nice and short version which does the above is below (and attached as tournielean.rb). I actually wrote this version after writing the other version because most of the entries to Ruby Quiz seem to be short. ./tournielean n where n is the number of teams to run it. #! /usr/bin/ruby class Numeric # Is the given number a power of self? # 16.isPowerOf(2) == true # 100.isPowerOf(2) == false def isPowerOf(other) i = 0 while (other ** i <= self) return true if other ** i == self i += 1 end false end end class Tournament # Recieves a list of team names in order of ranking with the best first. def initialize(teams) @eligible = teams @round = 0 end def createNextRound out = "Round #{@round += 1}: " inCurrentRound = [] until (@eligible.length.isPowerOf(2)) out += "#{@eligible.first} vs. bye, " inCurrentRound.push @eligible.shift end until (@eligible.empty?) winner = @eligible.shift loser = @eligible.pop out += "#{winner} vs. #{loser}, " inCurrentRound.push(winner) end @eligible = inCurrentRound out[0, out.length - 2] + "." end def createAllRounds out = "" until (@eligible.length == 1) out << createNextRound << "\n" end out# + "Winner: #{@eligible[0]}" end end t = Tournament.new((1..(ARGV[0].to_i)).to_a) puts t.createAllRounds --Boundary_(ID_7mMBSYuPFLAZYI71WIEG/w) Content-type: application/x-ruby; name=tournielean.rb Content-transfer-encoding: base64 Content-disposition: inline; filename=tournielean.rb IyEgL3Vzci9iaW4vcnVieQoKY2xhc3MgTnVtZXJpYwoJIyBJcyB0aGUgZ2l2ZW4gbnVtYmVy IGEgcG93ZXIgb2Ygc2VsZj8KCSMgMTYuaXNQb3dlck9mKDIpID09IHRydWUKCSMgMTAwLmlz UG93ZXJPZigyKSA9PSBmYWxzZQoJZGVmIGlzUG93ZXJPZihvdGhlcikKCQlpID0gMAoJCXdo aWxlIChvdGhlciAqKiBp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