Wednesday, October 22, 2008

Shuffling Arrays

Ever want to randomize an array of items? It's a task that, for some reason, I've had to do a lot in recent programs. So, I wrote a handy category on NSArray to handle the task.



@interface NSArray(Shuffle)
-(NSArray *)shuffledArray;


#import "NSArray-Shuffle.h"

@implementation NSArray(Shuffle)
-(NSArray *)shuffledArray

NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];

NSMutableArray *copy = [self mutableCopy];
while ([copy count] > 0)
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];

[copy release];
return array;