Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I "roll" for a 25% chance to get YES or NO?

Tags:

objective-c

I'd like to randomly generate a YES or NO based on a percentage

So I want to "roll" and have a 25% chance to hit YES, a 75% chance to hit NO

Was hoping someone could point me in the right direction on the best way to do this, maybe some article or something?

like image 551
korben Avatar asked Apr 05 '13 21:04

korben


2 Answers

All of the other answers seem to focus on the percentage of YES being 25%, which is a probability of 1/4. But what if the percentage is an arbitrary integer between 0 and 100?

BOOL randomBoolWithYesPercentage(int percentage) {
    return arc4random_uniform(100) < percentage;
}

Call it with the percentage, like randomBoolWithYesPercentage(25).

And what if the percentage can be fractional, like 37.6%? Then we need to get more sophisticated. This should suffice:

BOOL randomBoolWithYesPercentage(double percentage) {
    double r = 100 * (double)arc4random() / ((double)UINT32_MAX + 1);
    return r < percentage;
}
like image 101
rob mayoff Avatar answered Jan 21 '23 18:01

rob mayoff


Use a random function with an equal distribution and make it as likely as you want to equal one of the possible values

BOOL RollWithDenominator(NSInteger denominator)
{
  return 0 == arc4random_uniform(denominator);
}

For a 1/4 chance call RollWithDenominator(4);

like image 26
Paul.s Avatar answered Jan 21 '23 18:01

Paul.s