How to select range of values when using arc4random()
As pointed out in other posts below, it is better to use arc4random_uniform
. (When this answer was originally written, arc4random_uniform
was not available). Besides avoiding the modulo bias of arc4random() % x
, it also avoids a seeding problem with arc4random
when used recursively in short timeframes.
arc4random_uniform(4)
will generate 0, 1, 2 or 3. Thus you could use:
arc4random_uniform(51)
and merely add 50 to the result to get a range between 50 & 100 (inclusive).
To expand upon JohnK comment.
It is suggested that you use the following function to return a ranged random number:
arc4random_uniform(51)
which will return a random number in the range 0
to 50
.
Then you can add your lower bounds to this like:
arc4random_uniform(51) + 50
which will return a random number in the range 50
to 100
.
The reason we use arc4random_uniform(51)
over arc4random() % 51
is to avoid the modulo bias. This is highlighted in the man page as follows:
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.
In short you get a more evenly distributed random number generated.
int fromNumber = 10;int toNumber = 30;int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
Will generate randon number
between 10
and 30
, i.e. 11,12,13,14......29