ActiveState Code

Recipe 65435: Shuffling a list


How to randomly shuffle a list

Tcl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
proc K { x y } { set x }

proc shuffle4 { list } {
    set n [llength $list]
    while {$n > 0} {
	set j [expr {int(rand()*$n)}]
	lappend slist [lindex $list $j]
	incr n -1
	set temp [lindex $list $n]
	set list [lreplace [K $list [set list {}]] $j $j $temp]
    }
    return $slist
}

Discussion

See also the Shuffle a list ( http://www.purl.org/thecliff/tcl/wiki/941.html ) page on the wiki for a performance comparison of several algorithms for doing this. The algorithm presented here is number 4 on that page (by Stephen Cohen).

Sign in to comment