iOS学习笔记——随机打乱一个数组
常规方式:
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实现:
1 2 3 4 5 6 7 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];