Search code examples
iosmathprobabilityarc4random

Probability equation using arc4random()?


In my game I know I can use conditions for this, but I wanted to see if there was a math equation that would make it easier on me. I'd like to use arc4random().

What I need is:

  1. If my score is 1-20, probability: 1 out of 25
  2. If my score is 21-40, probability: 1 out of 20
  3. If my score is 41-60, probability: 1 out of 15
  4. If my score is 60+, probability: 1 out of 10.

Is this possible? And if so, how would I achieve this?

Thanks!


Solution

  • This should do the trick (hope it's clear!):

    int modNumber = 25;
    float alteredScore = score - (floor((score-1)/60) - 1) * 60;
    modNumber -= floor((alteredScore-1)/20) * 5;
    int result = arc4random() % modNumber;  // Or arc4random_uniform(modNumber) if you want to completely remove modulo bias, but beaing in mind the non-randomness (!) of arc4random and the size of modNumber I highly doubt it would make any real difference
    if (!result) {
        // Result is 0
        // Do stuff for the lucky person
    } else {
        // Make them miserable
    }