算法一
NSMutableArray *randSequence = [[NSMutableArray alloc] initWithCapacity:8];
for (int ii = 0; ii < 10; ++ii)
[randSequence addObject:[NSNumber numberWithInt:ii]];
for (int ii = 9; ii > -1; --ii) {
int r = arc4random() % 9
[randSequence exchangeObjectAtIndex:ii withObjectAtIndex:r];
}
算法二
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
// NSMutableArray_Shuffling.m
import "NSMutableArray_Shuffling.h"
@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
NSInteger nElements = count - i;
NSInteger n = (arc4random() % nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
网友评论