Randomizing Trick

Normally if programmer wants to randomize (ie) 1000 numbers and all numbers should be different than others (all numbers only once) he/she first randomizes number, then loops all ready randomed numbers and checks is it allready randomed.

In huge series of numbers to randomize, it might take pretty long time. Practically endless loop is nearly possible.

Option Explicit
Randomize Timer

Dim AS Integer Counter, Counter2, Check, Randomed, Times
    Times = 0 ' how many loops its needed to get 1000 seperate numbers
Dim AS Integer Numbers
    Numbers = 10000

Dim AS Integer RandArray(Numbers)
Dim AS Integer RandArray2(Numbers)

' Add numbers on array in order. 
For Counter = 1 TO Numbers
    RandArray2(Counter) = Counter
Next Counter

Counter = Numbers
DO
    Times = Times + 1
    Randomed = INT(RND * Counter) + 1
    RandArray(Counter) = RandArray2(Randomed)
      ' If Randomed wasnt biggest possible, we move it to location we just randomed and Counter can reduce
      ' with out fear that some number stays as "unrandomized"
      IF Randomed < Counter Then RandArray2(Randomed) = RandArray2(Counter)
Counter = Counter - 1
Loop Until Counter = 0

For Counter = 1 TO Numbers
    Print RandArray(Counter)
Next Counter

Print Times; " loops needed to fill array."
Print "Thats like "; Times - Numbers; " useless rounds this time."
END
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.