Created
February 4, 2014 06:50
-
-
Save solkar/8799171 to your computer and use it in GitHub Desktop.
shuffle NSMutableArray category
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 (Shuffling) | |
- (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+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_uniform(nElements) + i; | |
[self exchangeObjectAtIndex:i withObjectAtIndex:n]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extracted from http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray