Need to quickly shuffle an array, for a deck of cards or whatever? Here’s categories for NSArray and NSMutableArray to do that simply:
- (NSMutableArray*) shuffle {
NSUInteger n = [self count];
while (n > 1) {
NSUInteger k = rand() % n;
n--;
[self exchangeObjectAtIndex: n withObjectAtIndex: k];
}
return self;
}
The algorithm used here is the Fisher–Yates shuffle which we’ve forgotten far more numerical analysis than we’d need to have an actual opinion about, but hey if it’s popular it must be good, right?
5
NOV
NOV
0
Share