How to generate a random number

Fri, Jul 5

If you need to generate a random number within your app, you have to push aside Objective-C, as there is no class with a built-in random number generator. The alternative is to use C, among the functions available are: rand(), srand(), random(), srandom() and arc4random().

arc4random() tends to be preferred as it does not require seeding, the function automatically initializes itself.

// Get random value between 0 and 99
int x = arc4random() % 100;
 
// Get random number between 500 and 1000
int y =  (arc4random() % 501) + 500;

Update: thanks Dave Verwer and Kevin Conner for pointing out the advantages of arc4random_uniform.

Apple docs:

arc4random_uniform() will return a uniformly distributed random number less than upper_bound.

5 comments

The freely available, and BSD licensed, Mersenne twister also works quite handsomely on the iPhone.

by Alex on Jul 22, 2009. #

I tend to make a macro to do this:

#define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + arc4random() % ((__MAX__+1) – (__MIN__)))

by slimemoldjuice on Jul 22, 2009. #

Thank you!

by Ilya on Apr 4, 2011. #

thnaks… it helped..

by MANN on Jul 13, 2011. #

thanks

by yunas on Jan 25, 2012. #