Created
January 21, 2013 19:18
-
-
Save codeswimmer/4588483 to your computer and use it in GitHub Desktop.
This file contains 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
// NSMutableArray_Shuffling.h | |
#if TARGET_OS_IPHONE | |
#import <UIKit/UIKit.h> | |
#else | |
#include <Cocoa/Cocoa.h> | |
#endif | |
// This category enhances NSMutableArray by providing | |
// methods to randomly shuffle the elements. | |
@interface NSMutableArray (Shuffling) | |
- (void)shuffle; | |
@end |
This file contains 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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment