Question

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;
Was it helpful?

Solution 2

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++;

OTHER TIPS

Exclude it:

uint32_t identifier = 1; // << the number to exclude
uint32_t NIdentifiers = 1;
uint32_t NNumbers = 3;
uint32_t NPossibleIdentifiers = NNumbers - NIdentifiers;

uint32_t result = arc4random_uniform(NPossibleIdentifiers);
if (identifier == result)
 ++result;

Note: favor arc4random_uniform over arc4random and modulo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top