proc getBracket {participants} {
# Reorder participants according to strength
set participants [lsort -decreasing -index 2 $participants]
# Get number of participants
set L [llength $participants]
# Get number of participants above ideal number
set diff [expr {$L-pow(2,int(log($L)/log(2)))}]
# Get the stronger participants outside the brackets (they can enter finals or other directly)
set outside [lrange $participants 0 [expr {int($diff-1)}]]
# Remove excluded participants from bracket
set participants [lreplace $participants 0 [expr {int($diff-1)}]]
# Temporary list holder
set newlist ""
set count 1
# Add new ticket number to participants
foreach n $participants {
set a [lindex $n 0] ;# lassign isn't available in Tcl 8.4, but this part is only for formatting
set b [lindex $n 1]
set c [lindex $n 2]
# Format the output
lappend newlist [format "%-3s %-3s %-20s %-2s" $count $a $b $c]
incr count
}
# Set new participant list
set participants $newlist
# Get new number of participants
set L [llength $participants]
# Temporary placeholder for sequence insertion
set list [list]
# Final bracket list
set bracket [list]
for {set n 1} {$n <= $L} {incr n} {
# If ideal number, put itself
if {[regexp {\.0$} [expr {log($n)/log(2)}]]} {
lappend list $n
# If odd, take ((n-1)/2)th term
} elseif {$n % 2 == 1} {
lappend list [lindex $list [expr {($n-1)/2}]]
# If even, some more complicated number
} else {
lappend list [expr {[lindex $list [expr {($n/2)-1}]]+($n/2)}]
}
}
# Order participants according to generated sequence
for {set i 1} {$i <= [llength $list]} {incr i} {
set bracket [linsert $bracket [expr {[lindex $list [expr {$i-1}]]-1}] [lindex $participants [expr {$i-1}]]]
}
# Output
return [list {Main bracket} [join $bracket "\n"] {Outside bracket} [join $outside "\n"]]
}
set participants {
{1 John 0}
{2 Gagan 0}
{3 {Mike Tyson} 1}
{4 Gair 0}
{5 Gale 0}
{6 {Roy Johnes} 1}
{7 Galip 0}
{8 Gallagher 0}
{9 Garett 0}
{10 {Nikolai Valuev} 1}
{11 Garner 0}
{12 Gary 0}
{13 Gelar 0}
{14 Gershom 0}
{15 Gilby 0}
{16 Gilford 0}
{17 Arianna 2}
}
puts [join [getBracket $participants] "\n"]