title: "Different Random Number Algorithms in iOS Development with Objective-C (arc4random, random, srandom)"

date: "2012-06-18"

categories:

- "mobileinternet"
- "algorithms"
- "sourceandcoding"

tags: - "ccplusplus"
- "ios"
- "objective-c"
- "random"

Objective-C does not directly provide functions or methods for generating random data. However, we can directly use various random algorithms in C. The following are several commonly used random number algorithms, which can be referenced in the header file stdlib.h.

arc4random does not require a random seed and automatically generates a random seed when called. Returns a set of [0, X) int value = arc4random() % x; Returns a set of [1, X] int value = (arc4random() % x) + 1;

random()/rand() does not use a seed and returns any number within the range of long/int. Note that random returns long and rand returns int.

srandom(unsigned)/srand(unsigned) uses a random seed and returns any number between the parameter and RAND_MAX. Note that srandom can use unsigned long as a parameter.

It is important to note that the rand series of random numbers use pseudo-random algorithms, so it is recommended to use different random seeds when calling them. For example: srand(time(NULL))