source: trunk/p2p/random.tcl @ 5348

Last change on this file since 5348 was 3177, checked in by mmc, 7 years ago

Updated all of the copyright notices to reference the transfer to
the new HUBzero Foundation, LLC.

File size: 2.0 KB
Line 
1# ----------------------------------------------------------------------
2#  LIBRARY: randomization routines
3# ----------------------------------------------------------------------
4#  Michael McLennan (mmclennan@purdue.edu)
5# ======================================================================
6#  Copyright (c) 2004-2012  HUBzero Foundation, LLC
7#
8#  See the file "license.terms" for information on usage and
9#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
10# ======================================================================
11
12expr srand([clock seconds])
13
14# ----------------------------------------------------------------------
15#  USAGE: randomize <list> ?<pickThisMany>?
16#
17#  Scrambles the elements in a list and returns them in random order.
18#  Given a list of peer connections, for example, this function
19#  scrambles the order so that a "foreach" command can traverse them
20#  in a random order.  If <pickThisMany> is specified, then the list
21#  is truncated after that many random entries.  Instead of randomizing
22#  all 10,000 entries, for example, you can pick the first random 10.
23# ----------------------------------------------------------------------
24proc randomize {entries {pickThisMany -1}} {
25    set rlist ""
26    set rlen [llength $entries]
27    for {set i 0} {$i < $rlen} {incr i} {
28        # if we have the desired number of elements, then quit
29        if {$pickThisMany >= 0 && $i >= $pickThisMany} {
30            break
31        }
32
33        # pick a random element and add it to the return list
34        set nrand [expr {int(rand()*[llength $entries])}]
35        lappend rlist [lindex $entries $nrand]
36        set entries [lreplace $entries $nrand $nrand]
37    }
38    return $rlist
39}
40
41# ----------------------------------------------------------------------
42#  USAGE: random <list>
43#
44#  Picks one element at random from the given <list>.
45# ----------------------------------------------------------------------
46proc random {entries} {
47    set nrand [expr {int(rand()*[llength $entries])}]
48    return [lindex $entries $nrand]
49}
Note: See TracBrowser for help on using the repository browser.