How do I seed the rand() function in Objective-C?

inorganik picture inorganik · Aug 25, 2012 · Viewed 11.8k times · Source

Part of what I'm developing is a random company name generator. It draws from several arrays of name parts. I use the rand() function to draw the random name parts. However, the same "random" numbers are always generated in the same sequence every time I launch the app, so the same names always appear.

So I searched around SO, and in C there is an srand() function to "seed" the random function with something like the current time to make it more random - like srand(time(NULL)). Is there something like that for Objective-C that I can use for iOS development?

Answer

pasawaya picture pasawaya · Aug 25, 2012

Why don't you use arc4random which doesn't require a seed? You use it like this:

int r = arc4random();

Here's an article comparing it to rand(). The arc4random() man page says this about it in comparison to rand():

The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and random(3).

If you want a random number within a range, you can use the arc4random_uniform() function. For example, to generate a random number between 0 and 10, you would do this:

int i = arc4random_uniform(11);

Here's some info from the man page:

arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.