PDA

View Full Version : Random int not so random




chainprayer
May 29, 2010, 04:31 PM
I have a switch set up to select random values like this...

- (IBAction)randomResultGenerator {
int rNumber = rand() % 20;

switch (rNumber) {

case 0:
result.text = @"A.J.";
break;

case 1:
result.text = @"Abacus";
break;

etc...


Every time I launch my app it runs through the same order. Is there something I am doing wrong to generate a random number? They run in random order, but its the same random order every time.



robbieduncan
May 29, 2010, 04:40 PM
You haven't seeded the random number generator.

Bill McEnaney
May 29, 2010, 04:51 PM
Why not try the srand() function?

TiberiusXavier
May 29, 2010, 06:49 PM
Random numbers do not exist in programs. What is offered instead is a pseudo-random algorithm or function rand that generates a vast range of distribution values. This rand function is fully deterministic given the input value. This input value begins with the seeded value (0 by default) and is set by another function called srand. Most programmers attain another level of pseudo-random sequence by seeding the function using the system clock (theoretically never the same value for the lifespan of the application or by then it will never be noticeable.) This seeding is done like srand( time( 0 ) );.

Next is the distribution of this randomness. The quick (both CPU cyclewise and coding) is to modulo the return value of rand by the maximum value (and 0 being the minimum.) However, to get a uniform distribution over the range (the quick approach favors lower numbers), it would require a floating-point math operation of dividing the return value of rand by the MAX_RAND constant (which is platform specific!)

So to get a random number from minimum to maximum inclusively:
Quick:

srand( time( 0 ) ); // Do once at start-up and never again.
int randomInt = minimum + rand() % ( maximum - minimum + 1 ); // Integer between 0 and max


Slow:

srand( time( 0 ) ); // Do once at start-up and never again.
int randomInt = minimum + (int)( ( maximum - minimum + 1) * ( rand() / ( 1.0 + (double)RAND_MAX ) ) );

KoolStar
May 29, 2010, 10:32 PM
If you want random numbers everytime just use arc4random()