Skip to content

Instantly share code, notes, and snippets.

@codeswimmer
Created January 21, 2013 19:18
Show Gist options
  • Save codeswimmer/4588483 to your computer and use it in GitHub Desktop.
Save codeswimmer/4588483 to your computer and use it in GitHub Desktop.
// 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
// 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