My question is related to a tcl code which I found here:
Generate random number within specified range without REDUNDANCY in TCL
The code has been suggested as an answer to the question on the above side and it looks as follows:
set r -1; # Some value that definitely isn't in the sequence
for {set i 1} {$i < 31} {incr i} {
upvar 0 fnode($i) fnod($i)
while {$r == [set r [myRand 1 20]]} {
# Empty body
}
set fnod($i) $r; # Random number is generated between 1 to 20
}
I would like to understand it but I am confused because of this line:
upvar 0 fnode($i) fnod($i)
Why is this line in the code? The first array, fnode($i), does not occur earlier in the code. Therefore, it is should not be possible to apply upvar to it. And there doesn't seem to be any reason to introduce an alias fnod($i) for it.
Another important point: Why does this code guarantee that among 30 randomly generated numbers, 20 of them are distinct?
In the above code, myRand is the following proc (also suggested on the same side and by the same author):
proc myRand {min max} {
set range [expr {$max - $min + 1}]
return [expr {$min + int(rand() * $range)}]
}
It generates randomly an integer in the range [min, max].
I should also add: This code does not run in TclTutor 3.0b6. I get the following error message:
--------
bad variable name "fnod(1)": upvar won't create a scalar variable that looks like an array element
while executing
"upvar 0 fnode($i) fnod($i)"
Any help is welcome.
Thank you in advance!