hi need generate 30 random numbers without repeatations of numbers in tcl.
here code generate random number works fine, generate redundant numbers.
proc myrand { min max } { set maxfactor [expr [expr $max + 1] - $min] set value [expr int([expr rand() * 100])] set value [expr [expr $value % $maxfactor] + $min] return $value } {set 1} {$i < 31} {incr i} { upvar 0 fnode($i) fnod($i) set fnod($i) [myrand 1 20] ;# random number generated between 1 20 }
anyone please out.
code generate sequence of unique random numbers written this, won't work unless $nnums
less or equal $rmax
.
set nnums 30 set rmax 20 set nums {} if {$nnums > $rmax} { puts "you can't $nnums unique values range of 1 $rmax!" } else { while {[llength $nums] < $nnums} { set n [myrand 1 $rmax] if {$n ni $nums} {lappend nums $n} } set nums [linsert $nums 0 {}] {set 1} {$i <= $nnums} {incr i} { set fnod($i) [lindex $nums $i] } }
(when started writing answer, preoccupied notice trying 30 unique numbers 1-20 range, impossible, others have pointed out.)
there other problems code. don't need nested calls expr
:
expr [expr $max + 1] - $min # same expr {$max + 1 - $min}
so random number generator can written this:
proc myrand {min max} { expr {int(rand() * 100) % ($max + 1 - $min) + $min} }
but still more calculations necessary. version better:
proc myrand {min max} { expr {int(rand() * ($max + 1 - $min)) + $min} }
you can use this:
package require math ::math::random 1 21
(note 21, not 20!)
Comments
Post a Comment