Forum OpenACS Q&A: Response to Coding: db vs tcl: Fastest Random Loop

Collapse
Posted by Michael A. Cleverly on
There are n! ways to order n-items. For six items then, 6! equals 720 unique combinations. Your if code above enumerates 6, excluding the other 714 possibilities.

The following Tcl proc will "randomize" a list of elements for you:

proc randomize_list {original} {
    set randomized [list]
    set size [expr {[llength $original] + 1}]
 
    while {[incr size -1]} {
        set i [expr {int(rand() * $size)}]
        lappend randomized [lindex $original $i]
        set original [lreplace $original $i $i]
    }
 
    return $randomized
}