Thanks, this was fun!
class Tournament
attr_reader :list
def initialize players
raise “Must be a positive number of players” if players < 1
@players = players
@list = Array.new(players) { |i| i+1 }
# Add 'bye's up to the next power of 2
next_power = 2 ** sprintf("%b",players).length
unless players == next_power / 2
(players+1).upto(next_power) { @list << 'bye' }
end
@list = generate @list
end
def generate list
len = list.length
return list if len <= 2
left = list[0…(len/4-1)]+list[-(len/4)…-1]
right= list[(len/4)…-(len/4+1)]
[generate(left),generate(right)]
end
end
puts “Test tournaments from 1 to 16 in size:”
1.upto(16) do |players|
puts Tournament.new(players).list.inspect
end