Welcome, guest | Sign In | My Account | Store | Cart

How to randomly shuffle a list

Tcl, 13 lines
 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
}

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).

Created by Jeff Hobbs on Thu, 21 Jun 2001 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks