source: trunk/p2p/random.tcl @ 1251

Last change on this file since 1251 was 1251, checked in by mmc, 15 years ago

Added first cut of P2P network for job management. See README in this
directory for details.

File size: 1.6 KB
Line 
1# ----------------------------------------------------------------------
2#  LIBRARY: randomization routines
3# ----------------------------------------------------------------------
4#  Michael McLennan (mmclennan@purdue.edu)
5# ======================================================================
6#  Copyright (c) 2008  Purdue Research Foundation
7# ======================================================================
8
9expr 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# ----------------------------------------------------------------------
21proc 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}
Note: See TracBrowser for help on using the repository browser.