Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chainprayer

macrumors 6502a
Original poster
Feb 10, 2008
638
2
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.
 
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 ) ) );
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.