Last active
June 6, 2016 15:26
-
-
Save mmick66/a8327deebd9391aa9b4b0bcd0337d9da to your computer and use it in GitHub Desktop.
Extension to the NSMutableArray class to provide randomization functions
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
#import <Foundation/Foundation.h> | |
@interface NSMutableArray (WSRandom) | |
- (id) objectAtRandomIndex; | |
- (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
#import "NSMutableArray+WSRandom.h" | |
@implementation NSMutableArray (WSRandom) | |
- (id) objectAtRandomIndex | |
{ | |
switch (self.count) | |
{ | |
case 0: | |
return nil; | |
break; | |
case 1: | |
return self.firstObject; | |
break; | |
default: | |
return self[arc4random_uniform((u_int32_t)self.count)]; | |
break; | |
} | |
} | |
- (id) popAtRandomIndex | |
{ | |
id obj = [self objectAtRandomIndex]; | |
if(obj) | |
{ | |
[self removeObject:obj]; | |
} | |
return obj; | |
} | |
- (void) shuffle | |
{ | |
// Fisher–Yates shuffle | |
NSUInteger i = self.count; | |
if(i < 2) | |
{ | |
return; | |
} | |
while (i > 1) | |
{ | |
i--; | |
NSUInteger j = arc4random_uniform((u_int32_t)i); | |
[self exchangeObjectAtIndex:i withObjectAtIndex:j]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment