# Random int not so random

Discussion in 'iOS Programming' started by chainprayer, May 29, 2010.

1. ### chainprayer macrumors 6502a

Joined:
Feb 10, 2008
#1
I have a switch set up to select random values like this...

Code:
```- (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.

2. ### robbieduncan Moderator emeritus

Joined:
Jul 24, 2002
Location:
London
#2
You haven't seeded the random number generator.

Joined:
Apr 29, 2010
4. ### TiberiusXavier macrumors member

Joined:
Apr 18, 2010
Location:
Chicago
#4
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:
Code:
```srand( time( 0 ) );  // Do once at start-up and never again.
int randomInt = minimum + rand() % ( maximum - minimum + 1 );  // Integer between 0 and max
```
Slow:
Code:
```srand( time( 0 ) );  // Do once at start-up and never again.
int randomInt = minimum + (int)( ( maximum - minimum + 1) * ( rand() / ( 1.0 + (double)RAND_MAX ) ) );
```

5. ### KoolStar macrumors demi-god

Joined:
Oct 16, 2006
Location:
Kentucky
#5
If you want random numbers everytime just use arc4random()