Re-arrange NSArray/MSMutableArray in random order

2019-01-08 23:20发布

问题:

I'm using NSArray/NSMutable array to store different objects. Once all the objects are added, I want to re-arrange them in random order. How can I do it?

回答1:

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];
}


回答2:

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


回答3:

Link GameplayKit/GameplayKit.h in your project then

#import <GameplayKit/GameplayKit.h>

Now you can use the property shuffledArray.

NSArray *randomArray = [yourArray shuffledArray];


标签: iphone random