user1283776 user1283776 - 3 months ago 10
Objective-C Question

Make sure that random() does not return 0?

I'm looking at the documentation for random():

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/srandomdev.3.html#//apple_ref/c/func/random

It returns successive pseudo-random numbers in the range from 0 to (2**31)-1.

I don't want it to return 0 ever.

I'm thinking about writing:

long rand = random() + 1;


But if I'm not mistaken, long can be 32-bits on a 32-bit processor. I guess I would risk stack overflow then.

What is the best approach to getting a random number between 1 and (2**31)-1?

Answer
long rand = 0;
while (rand == 0) {
    rand = random();
}

This will almost absolutely certainly run exactly once. In a very, very rare case (that will never happen), it will run twice.

(Note that this is just a simplified version of how arc4random_uniform works. If you can use that function, as suggested by Jeff, you should.)

Comments