What is the best way to generate random numbers using Objective-C on iOS?
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.
Asked
Active
Viewed 5.3k times
22
6 Answers
71
There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):
int r = arc4random() % 5;

Community
- 1
- 1

newtonapple
- 4,123
- 3
- 33
- 31
-
115 if they want it from 0 to 4 – user102008 Mar 15 '11 at 01:28
-
It gives unbiased results for all n, rather than only power-of-2 n, see the man page – Catfish_Man May 09 '13 at 15:36
15
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
- 15,187
- 13
- 60
- 91
10
You should seed the random number generator with the current time.
srand(time(0));

Niyaz
- 53,943
- 55
- 151
- 182
6
How random do you need? If you want random enough for crypto, then use SecRandomCopyBytes().
3
Call srand()
at the start of your program, it'll reseed random number generator

vava
- 24,851
- 11
- 64
- 79
2
Simple function for random number generation:
int r = arc4random() % 42; // generate number up to 42 (limit)

Regexident
- 29,441
- 10
- 93
- 100

Himanshu padia
- 7,428
- 1
- 47
- 45
-
While being redundant as an answer, I like how the number 42 is being used instead of 5 here. – Toastor May 08 '13 at 14:28
-
1As I want to generate random number up to 41 so I have given 42, so it will generate between 0 to 41 including 0 & 41, as I want to use 41. – Himanshu padia May 09 '13 at 05:13
-
Fair enough. However, you are strongly encouraged to read "The Hitchhikers Guide to the Galaxy" - I believe it is a non-optional reading for programmers in general. – Toastor May 10 '13 at 13:04
-
1