I am using rand() function, but it always uses the same random sequence. Is there a random function that seeds with the clock value? And how would I do this?
Asked
Active
Viewed 80 times
0
-
2arc4random(). Answered here: http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c – colbadhombre Jan 11 '12 at 20:11
2 Answers
1
rand()
requires you to specify the seed. The best way to specify a seed is to use the current time.
// specify the seed
srand(time(NULL));
Or you can use arc4random.

taskinoor
- 45,586
- 12
- 116
- 142
-
1If you have any interest in security do not seed with the clock, that is just to easy to crack. – zaph Jan 11 '12 at 20:41
0
You are meant to seed rand()
and random()
(slightly bigger space) yourself, with their respective seed functions, before using them. You can use the time, or whatever other value you desire:
srand(time(0));
srandom(time(0));
Here we get the system time; obviously passing a constant will produce the same sequence every run.
You can also use arc4random()
which generates very high-quality random bits and seeds itself using /dev/random.

jscs
- 63,694
- 13
- 151
- 195
-
1Use `arc4random()`, there really is little reason not to and there ae no seeding issues. – zaph Jan 11 '12 at 20:39