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.
views:
7647answers:
5
+1
A:
Call srand()
at the start of your program, it'll reseed random number generator
vava
2009-02-04 07:16:05
+6
A:
You should seed the random number generator with the current time.
srand(time(0));
Niyaz
2009-02-04 07:16:12
+3
A:
How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().
Graham Lee
2009-02-04 07:18:17
+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
2009-02-04 07:29:41
+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
2009-02-04 16:44:35