Skip to content

Instantly share code, notes, and snippets.

@mmick66
Last active June 6, 2016 15:26
Show Gist options
  • Save mmick66/a8327deebd9391aa9b4b0bcd0337d9da to your computer and use it in GitHub Desktop.
Save mmick66/a8327deebd9391aa9b4b0bcd0337d9da to your computer and use it in GitHub Desktop.
Extension to the NSMutableArray class to provide randomization functions
#import <Foundation/Foundation.h>
@interface NSMutableArray (WSRandom)
- (id) objectAtRandomIndex;
- (void) shuffle;
@end
#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