Shuffle NSArray

133 views Asked by At

I got an NSMutableArray with a rather small number of objects that varies from 1 to max 20.

When user taps a button I want to select one random object and display it. I've tried shuffling the array:

srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++)     {
    NSInteger randInt = (random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];

}

And then select a random index using arc4random() but I get many repetitions. I do not want to removeObjectAtIndex as this would only reduce my array to zero and then crash. Is there a way to repopulate the array with the same objects once reached zero and start over again?

Thanks

2

There are 2 answers

0
George Asda On BEST ANSWER

I managed to "solve" my issue by doing the following: It maybe messy but I would like some input on this.

NSUInteger randomIndex = arc4random()% [_someArray count];

    if (array.count == 0) { //check if array is empty and add the randomIndex
        [array addObject:@(randomIndex)];
        randomTitle = [[_someArray objectAtIndex:randomIndex] myText];

        // NSLog(@"array is empty");
        // NSLog(@"my array content %@", array);
    }

    else if (array.count > 0 && array.count < _someArray.count) {//check if array has already an object and check if this is unique and add it to the array. if not run the loop again.

          NSLog(@"array is betwen 0 and _someArray.count");

        if([array indexOfObject:@(randomIndex)] == NSNotFound) {
            [array addObject:@(randomIndex)];
       randomTitle = [[_someArray objectAtIndex:randomIndex] myText];

          //  NSLog(@"unique number in array");
        }

        else {

            [self loopBackTheAction];

            // NSLog(@"number is alreday in array");
        }
    }

   else if (array.count == _someArray.count) {//check if the array is full and empty it. run the loop again.

       [array removeAllObjects];
       [self loopBackTheAction];

       //  NSLog(@"array is full running again the loop");
    }
1
Quentin Hayot On

If you just need to pick a random object, you can use the following. It will be much more efficient than actually shuffling the array.

uint32_t rnd = arc4random_uniform([array count]);

MyObject *randomObject = [array objectAtIndex:rnd];

Credit to this answer from Adam.