Random but unique
miscdas at boxfrog.com
miscdas at boxfrog.com
Sun Jan 12 03:27:01 EST 2003
Here is the technique that I used in another app. It goes through the list
only one time, swapping a randomly chosen value from your list with the
last element of the list, where the last element is decremented in each
pass.
I decided to make a swap on EVERY pass, rather than checking to see if a
swap is required, because until the very last pass the probablity of needing
to swap is always greater than 50:50.
For a list L comprising n elements.
Begin loop at i=n and decrement i by 1.
Generate integer random number R in the range 1 through i.
Set Temp = L(i)
Set L(i) = L(R)
Set L(R) = Temp
Next i
So, on the first pass, the value of last element is swapped with the value
of the randomly generated element. On the final pass, the value of element 2
is swapped with the value of element 1. Because a swap is made with the
element L(i), you never have to worry about a duplicate value.
miscdas
More information about the use-livecode
mailing list