1 | # ---------------------------------------------------------------------- |
---|
2 | # LIBRARY: randomization routines |
---|
3 | # ---------------------------------------------------------------------- |
---|
4 | # Michael McLennan (mmclennan@purdue.edu) |
---|
5 | # ====================================================================== |
---|
6 | # Copyright (c) 2008 Purdue Research Foundation |
---|
7 | # ====================================================================== |
---|
8 | |
---|
9 | expr srand([clock seconds]) |
---|
10 | |
---|
11 | # ---------------------------------------------------------------------- |
---|
12 | # USAGE: randomize <list> ?<pickThisMany>? |
---|
13 | # |
---|
14 | # Scrambles the elements in a list and returns them in random order. |
---|
15 | # Given a list of peer connections, for example, this function |
---|
16 | # scrambles the order so that a "foreach" command can traverse them |
---|
17 | # in a random order. If <pickThisMany> is specified, then the list |
---|
18 | # is truncated after that many random entries. Instead of randomizing |
---|
19 | # all 10,000 entries, for example, you can pick the first random 10. |
---|
20 | # ---------------------------------------------------------------------- |
---|
21 | proc randomize {entries {pickThisMany -1}} { |
---|
22 | set rlist "" |
---|
23 | set rlen [llength $entries] |
---|
24 | for {set i 0} {$i < $rlen} {incr i} { |
---|
25 | # if we have the desired number of elements, then quit |
---|
26 | if {$pickThisMany >= 0 && $i >= $pickThisMany} { |
---|
27 | break |
---|
28 | } |
---|
29 | |
---|
30 | # pick a random element and add it to the return list |
---|
31 | set nrand [expr {int(rand()*[llength $entries])}] |
---|
32 | lappend rlist [lindex $entries $nrand] |
---|
33 | set entries [lreplace $entries $nrand $nrand] |
---|
34 | } |
---|
35 | return $rlist |
---|
36 | } |
---|