# Quiz 105 Solution - now with Trees!

**URL:** <https://www.ruby-forum.com/t/quiz-105-solution-now-with-trees/79178>\
**Category:** Ruby\
**Created:** [December 12, 2006, 10:08pm UTC](https://www.ruby-forum.com/t/quiz-105-solution-now-with-trees/79178 "2006-12-12T22:08:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![johnnybutler7](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8491ac/32.png) [@johnnybutler7](https://www.ruby-forum.com/u/johnnybutler7)\
**Post date:** [December 12, 2006, 10:08pm UTC](https://www.ruby-forum.com/t/quiz-105-solution-now-with-trees/79178/1 "2006-12-12T22:08:45Z")

</div>

Its not quite as clean as I’d like but there are other things I should  
be  
doing…

class Tournament  
attr\_reader :list

def initialize players  
raise “Must be more than one player in the tournament!” if players \<  
2  
@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

def to\_s  
lines = []  
depth = sprintf("%b",@list.flatten.length).length - 1  
title = “”  
1.upto(depth) { |r| title += sprintf( “R%d “, r ) }  
lines \<\< title  
lines \<\< (”=” \* title.length)  
lines \<\< to\_a(@list)  
lines.join("\n")  
end

# recursively build the tree display

def to\_a list = @list  
lines = []  
return lines if list.length \< 2  
if list[0].is\_a? Array  
left = to\_a(list[0]).flatten  
right = to\_a(list[1]).flatten  
indent = (left + right).collect { |i| i.length }.max  
all = left[0…(left.length / 2)]  
left[(left.length / 2 + 1)…-1].each do |i|  
all \<\< ((i + (" “\*indent))[0…(indent-1)] + “|”)  
end  
all \<\< (” “\*indent) + “|—”  
right[0…(right.length / 2 - 1)].each do |i|  
all \<\< ((i + (” “\*indent))[0…(indent-1)] + “|”)  
end  
all \<\< right[(right.length / 2)…-1]  
else  
return [list[0].to\_s, “—”, " |—”, “—”, list[1].to\_s]  
end  
end  
end
