views:

7647

answers:

5

What is the best way to generate random numbers using Objective C on the iPhone?
If I use (int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0) to generate a number from 0 to 4, every time I start the program on the iPhone it generates the same numbers to start off with.

+1  A: 

Call srand() at the start of your program, it'll reseed random number generator

vava
+6  A: 

You should seed the random number generator with the current time.

srand(time(0));
Niyaz
+3  A: 

How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().

Graham Lee
+17  A: 

There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):

int r = arc4random() % 4;
newtonapple
+4  A: 

i use

#define RANDOM_SEED() srandom(time(NULL))
#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))

so you can give a min and max

Andy Jacobs