您的位置:首页 > 移动开发 > IOS开发

iOS学习笔记——随机打乱一个数组

2012-05-18 10:53 337 查看
常规方式:

?View Code OBJC

1
2
3
4
5
6

NSMutableArray *newArray;
for(int i = 0; i< count; i++)
{
int m = (arc4random() % (count - i)) + i;
[newArray exchangeObjectAtIndex:i withObjectAtIndex: m];
}

注意,这里不能用rand(),要用arc4random()。rand()需要srandom(time(NULL));生成种子,且不是真正的伪随机数发生器;而arc4random()运行时,自动生成种子,且是真正的伪随机数发生器。

也可以使用NSMutableArray的Category实现:

?View Code OBJC

1
2
3
4
5
67
8
9
10
11
12
13
14

@interface NSMutableArray (Shuffling)
- (void) shuffle;
@end

@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
int count = [self count];
for (int i = 0; i < count; ++i) {
int n = (arc4random() % (count - i)) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end

使用:[newArray shuffle];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐