Re-arrange NSArray/MSMutableArray in random order

NSUInteger count = [yourMutableArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
   int nElements = count - i;
   int n = (arc4random() % nElements) + i;
   [yourMutableArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
    [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}

Link GameplayKit/GameplayKit.h in your project then

#import <GameplayKit/GameplayKit.h>

Now you can use the property shuffledArray.

NSArray *randomArray = [yourArray shuffledArray];

Tags:

Iphone

Random