patrick
patrick

Reputation: 9742

What is the most efficient way to get a random odd or even number?

So off the top of my head, I can think of a few solutions (focusing on getting random odd numbers for example):

int n;
while (n == 0 || n % 2 == 0) {
    n = (arc4random() % 100);
}

eww.. right? Not efficient at all..

int n = arc4random() % 100);
if (n % 2 == 0) n += 1;

But I don't like that it's always going to increase the number if it's not odd.. Maybe that shouldn't matter? Another approach could be to randomize that:

int n = arc4random() % 100);
if (n % 2 == 0) {
    if (arc4random() % 2 == 0) {
       n += 1;
    else {
       n -= 1;
    }
 }

But this feels a little bleah to me.. So I am wondering if there is a better way to do this sort of thing?

Upvotes: 0

Views: 748

Answers (2)

dfb
dfb

Reputation: 13289

Generate a random number and then multiply it by two for even, multiply by two plus 1 for odd.

In general, you want to keep these simple or you run the risk of messing up the distribution of numbers. Take the output of the typical [0...1) random number generator and then use a function to map it to the desired range.

FWIW - It doesn't look like you're skewing the distributions above, except for the third one. Notice that getting 99 is less probable than all the others unless you do your adjustments with a modulus incl. negative numbers. Since..

P(99) = P(first roll = 99) + P(first roll = 100 & second roll = -1) + P(first roll = 98 & second roll = +1)

and P(first roll = 100) = 0

Upvotes: 6

symcbean
symcbean

Reputation: 48387

If you want a random set of binary digits followed by a fixed digit, then I'd go with bitwise operations:

 odd = arc4random() | 1; 
 even = arc4random() & ~ 1;  

Upvotes: 3

Related Questions