【问题标题】:How to randomize an NSMutableArray? [duplicate]如何随机化 NSMutableArray? [复制]
【发布时间】:2011-06-06 16:52:02
【问题描述】:
【问题讨论】:
标签:
objective-c
nsmutablearray
shuffle
【解决方案1】:
以下是一些示例代码:
遍历数组,随机切换一个对象的位置。
for (int x = 0; x < [array count]; x++) {
int randInt = (arc4random() % ([array count] - x)) + x;
[array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
【解决方案2】:
@interface NSArray (Shuffling)
- (NSArray *)shuffledArray;
@end
@implementation NSArray (Shuffling)
- (NSArray *)shuffledArray {
NSMutableArray *newArray = [[self mutableCopy] autorelease];
[newArray shuffle];
return newArray;
}
@end
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
@implementation NSMutableArray (Shuffling)
- (void)shuffle {
@synchronized(self) {
NSUInteger count = [self count];
if (count == 0) {
return;
}
for (NSUInteger i = 0; i < count; i++) {
NSUInteger j = arc4random() % (count - 1);
if (j != i) {
[self exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
}
@end
但是请记住,这种洗牌是merely pseudorandom洗牌!