我正在使用NSArray / NSMutablearray来存储不同的对象。一旦添加了所有对象,我想以随机顺序重新排列它们。我该怎么做?
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)];
}
然后在你的项目中链接GameplayKit / GameplayKit.h
#import <GameplayKit/GameplayKit.h>
现在您可以使用属性shuffledArray。
NSArray *randomArray = [yourArray shuffledArray];
斯威夫特4
let count = self.arrayOfData.count
for (index, _) in self.arrayOfData.enumerated()
{
let nTempElement = count - index
let swapIndexwith = (Int(arc4random()) % nTempElement) + index
arrayOfData.swapAt(index, swapIndexwith)
}