Search code examples
iosrandomarc4random

New arc4random()%x; different from Previous number


I have this line of code to calculate a random number:

    myRand = arc4random()%24; //0:23

What's the most efficient way of adding to this in order for this not to generate the same number it previously generated.

I'm not trying to shuffle all 24, as I do want repeats, just preferably not 2 of the same number directly after each other...

I thought of storing the previous number separately, then comparing it and if matching, just do it again, but I couldn't figure out away if for example the same number came out 3 times in a row... Unlikely I know, but it's possible.

Thanks.


Solution

  • Keep a reference to the previously generated number in an ivar.

    NSInteger lastRandom;
    

    and initialize it to something like -1.

    Then when you want a new random number you can do something like:

    NSInteger newRandom;
    do {
        newRandom = arc4random_uniform(24);
    while (newRandom != lastRandom);
    lastRandom = newRandom;
    

    This little loop will ensure your new random number is different from the last you generated.