Reputation: 3336
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.
Upvotes: 0
Views: 84
Reputation: 126117
What you're looking for is much like a card shuffle: you want 24 values to come up in a randomized order, and like cards you want to take each out of the deck after it comes up so it doesn't come up again (until you reshuffle the deck).
GameplayKit in iOS 9 and later provide utilities for randomization tasks like this. In particular, this one is solved by the GKShuffledDistribution
class:
id<GKRandom> dist = [GKShuffledDistribution distributionForDieWithSideCount:24];
myRand = [dist nextInt];
This one doesn't repeat until all 24 values have been exhausted.
More generally, using GKRandom
(etc) instead of arc4random
(etc) gives you multiple options for controlling randomized behaviors in your game: making sure that different randomized game systems don't influence each other, making sure you can repeat certain random sequences for testing or between client and server, making random numbers that follow a specific pattern, and so on.
Upvotes: 0
Reputation: 318794
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.
Upvotes: 2