Question

I'm trying to create a NSMutableArray in Xcode 5 where I randomly generate a number between 1 and 12 and store them as integers. The problem is sometimes it will generate the same number twice, which is not desirable.

//Load array
NSMutableArray *theSequence = [[NSMutableArray alloc] init];

//Generate the Sequence
for (NSInteger i=0; i < difficultyLevel; i++) {
    int r = arc4random()%12 + 1;

    //Check here if duplicate exists
    [theSequence addObject:[NSNumber numberWithInteger:r]];
}

Where difficultyLevel is currently 4, as there should be 4 integers stored.

I've tried other answers on Stack Overflow with no success, would anyone be able to tailor some sort of loop before [theSequence addObject:..] so that when I show the numbers in a label they are unique? Thank you in advance!

Harry

Was it helpful?

Solution

Since the order of the ints does not matter (they are random, anyway) replacing NSMutableArray container with NSMutableSet will let you avoid duplicates. All you need to do now is check the size of the container, and stop when you reach the desired size of four:

NSMutableSet *theSequence = [NSMutableSet set];

do {
    int r = arc4random()%12 + 1;
    [theSequence addObject:[NSNumber numberWithInteger:r]];
} while (theSequence.count != difficultyLevel);

Note: If for some reason the insertion order is important, you can use NSMutableOrderedSet.

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