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.

NSArray-Shuffle.h

#import

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


NSArray-Shuffle.m

#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;
}
@end

No comments:

Post a Comment