Re-arrange NSArray/MSMutableArray in random order

2019-01-08 23:16发布

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?

标签: iphone random
3条回答
叛逆
2楼-- · 2019-01-08 23:57

Link GameplayKit/GameplayKit.h in your project then

#import <GameplayKit/GameplayKit.h>

Now you can use the property shuffledArray.

NSArray *randomArray = [yourArray shuffledArray];
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-09 00:07
// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
    [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
查看更多
甜甜的少女心
4楼-- · 2019-01-09 00:08
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];
}
查看更多
登录 后发表回答