Search code examples
iosintarc4random

Take out number in range arc4random ( )%x


I am using arc4random to generate a random number. I generate a number between 0 and 2. This is an identifier for a color-change in the game loop. If the number is equal to 1 the following generation should exclude the number 1. How can I do this?

int x = arc4random()%3;

Solution

  • There are two primary ways to do this.

    The simpler but potentially less efficient:

    int x;
    do {
        x = arc4random() % 3;
    } while (x == 1);
    

    or slightly more complex but more deterministic:

    int x = arc4random() % 2;
    if (x > 0) x++;