Skip to content

Instantly share code, notes, and snippets.

@dbrajkovic
Created October 10, 2012 16:21
Show Gist options
  • Save dbrajkovic/3866678 to your computer and use it in GitHub Desktop.
Save dbrajkovic/3866678 to your computer and use it in GitHub Desktop.
NSMutableArray (Shuffle)
@interface NSMutableArray (Shuffle)
- (void)shuffle;
@end
#import "NSMutableArray+Shuffle.h"
static NSUInteger random_below(NSUInteger n) {
NSUInteger m = 1;
// Compute smallest power of two greater than n.
// There's probably a faster solution than this loop, but bit-twiddling
// isn't my specialty.
do {
m <<= 1;
} while(m < n);
NSUInteger ret;
do {
ret = random() % m;
} while(ret >= n);
return ret;
}
@implementation NSMutableArray (ArchUtils_Shuffle)
- (void)shuffle {
// http://en.wikipedia.org/wiki/Knuth_shuffle
for(NSUInteger i = [self count]; i > 1; i--) {
NSUInteger j = random_below(i);
[self exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment