我正在使用NSArray/NSMutable数组来存储不同的对象.一旦添加了所有对象,我想以随机顺序重新排列它们.我该怎么做?
Nev*_*vin 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];
}
Run Code Online (Sandbox Code Playgroud)
小智 26
// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
[array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8424 次 |
| 最近记录: |