Created
October 10, 2012 16:21
-
-
Save dbrajkovic/3866678 to your computer and use it in GitHub Desktop.
NSMutableArray (Shuffle)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSMutableArray (Shuffle) | |
- (void)shuffle; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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