以随机顺序重新排列NSArray / MSMutableArray

问题描述 投票:14回答:4

我正在使用NSArray / NSMutablearray来存储不同的对象。一旦添加了所有对象,我想以随机顺序重新排列它们。我该怎么做?

iphone random
4个回答
55
投票
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];
}

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

0
投票

然后在你的项目中链接GameplayKit / GameplayKit.h

#import <GameplayKit/GameplayKit.h>

现在您可以使用属性shuffledArray。

NSArray *randomArray = [yourArray shuffledArray];

0
投票

斯威夫特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)
}
© www.soinside.com 2019 - 2024. All rights reserved.