random.tcl

random.tcl

Note that the initial value is UNIX-specific, in that it checks the last access time of the current tty and uses that as a random number seed. Feel free to change that to any other appropriate value.
set lastvalue [expr [file atime [exec tty]]%65536]
 
proc rawrand {} {
    global lastvalue
# per Knuth 3.6:
# 65277 mod 8 = 5 (since 65536 is a power of 2)
# c/m = .5-(1/6)\sqrt{3}
# c = 0.21132*m = 13849, and should be odd.
    set lastvalue [expr (65277*$lastvalue+13849)%65536]
    set lastvalue [expr ($lastvalue+65536)%65536]
    return $lastvalue
}
proc rand {base} {
    set rr [rawrand]
    return [expr ($rr*$base)/65536]
}
# knuth 3.4.2, algorithm P
proc shuffledeck {} {
  global cardindex
    set index 1
    foreach suitname {heart club spade diamond} {
        foreach cardname {ace 2 3 4 5 6 7 8 9 10 jack queen king} {
            set cardindex($index) ${cardname}_$suitname
            incr index
        }
    }
 
    for {set j 52} {$j>1} {incr j -1} {
        set k [expr [rand 52]+1]
        set temp $cardindex($k)
        set cardindex($k) $cardindex($j)
        set cardindex($j) $temp
    }
}