#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