简体   繁体   中英

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

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?

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 (2 1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2 32)-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.

The functions rand() and srand() are part of the Standard C Library and like the rest of the C library fully available for you to us in iOS development with Objective-C. Note that these routines have been superseded by random() and srandom() , which have almost identically calling conventions to rand() and srand() but produce much better results with a larger period. There is also an srandomdev() routine which initializes the state of the random number generator using the random number device. These are also part of the Standard C Library and available for use on iOS in Objective-C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM