views:

193

answers:

2

I have a very simple iPhone app that requires a random integer from 1-100.

I have a button that calls the random number function then displays it.

-(IBAction)buttonReleased;
{
    srandom(time(NULL)); 
    int theNum = random() % 100 + 1;
    numberDisplay.text = [NSString stringWithFormat:@"%d", theNum];
}

The problem is, if I press the button quickly, sometimes it won't display a new random number.

+7  A: 

The problem is you're seeding with time.

time is only updated every second, so if you click it within the second, you will seed the generator with the same number, which means you'll be getting the same number.

You should only be seeding once, at the start of the application.

GMan
doh! Newbie error #31415 and counting. Thanks.
willc2
Also, one should seed with something that has more precision than time. Try (CFAbsoluteTimeGetCurrent() * 1000)
rpetrich
Why, if I'm seeding just once at app start time? I want to learn.
willc2
Why use a higher timer precision? You don't really need to if you seed at the beginning. However, if you want to get more grimy, a good seed needs good random bits. Time isn't terribly random, since the lower bits are getting updating every second while the higher bits are relatively static. By using a higher precision timer the higher bits will change more often, giving a more random seed. That all said, for the sake of just a good ol'd random number, seeding with `time` at the start and forgetting about it works great.
GMan
+2  A: 
srandom(time(NULL));

Don't do that every time you generate a random number. Do it once, when your application starts.

Reason: Every time you call srandom() with a specific number, you'll get the same sequence of pseudo-random numbers from random(). So if you call your function twice in the same second, you'll get the same number.

user9876