Interview Questions

Is there a better way to generate a random integer than SilkTest's RandInt() function?

SilkTest Questions and Anwsers


(Continued from previous question...)

71. Is there a better way to generate a random integer than SilkTest's RandInt() function?

Is there a better way to generate a random integer than SilkTest's RandInt() function? I need true random numbers that going through a loop will give a diffrent random number each time. How RandInt does it is you get the same number on a fast loop.
I did make a RandomInt() function (see below), which helps on general random numbers since it is using RandSeed(), but on a loop that just grabs some random numbers, I still get the same numbers.
Anyone have a better way?
[CODE]
[ ] // Function: RandomInt
[ ] // Arguments: 1) iMin = Integer of Minimal value
[ ] // 2) iMax = Integer of maxium value
[ ] // Returns: random integer withing iMin and iMax
[-] INTEGER RandomInt(INTEGER iMin, INTEGER iMax, INTEGER iSeed optional)
[ ] INTEGER iRandom
[ ]
[-] if (iSeed == NULL)
[ ] iSeed = GetDateTimePart (GetDateTime (), DTP_SECOND) * GetDateTimePart (GetDateTime (), DTP_SECOND)
[ ]
[ ]
[ ] RandSeed (iSeed)
[ ] iRandom = RandInt(iMin, iMax)
[ ]
[-] if (DEBUG)
[ ] print ("Random Seed = {iSeed} Random Int = {iRandom}")
[ ]
[ ] return iRandom
[ ]
[/CODE]



Answer1:
Most programming languages provide random number based on what is called a pseudo-random sequence. This provides the appearance of random selection via a list that is seeded automatically by the system or by a command by the programmer. Either way it is still a randomized repeating list.
I don't know what to tell you except that you could try to reseed the generator after some number of iterations. the number of iterations could be randomized to vary the reseed interval. The seed could be based on a number representing the number of seconds (in integer form) since some fixed point in the past. This process probably would not repeat but sequences of integers could repeat unless the pseudo-random sequence is itself randomized by the seed instead of just the starting point within the sequence. I don't know the answer to that one. Otherwise your best hope might be a dll designed to provide a random number.

Answer2:
Try to have your function sleep a random time (1-3 seconds or so) and after the sleep call the RandInt () function.
You sort of call the RandInt twice one in each other. that doubles your Randomness chances.

(Continued on next question...)

Other Interview Questions