NSArray+DERandomization

#import <Foundation/Foundation.h>

 

@interface NSArray (DERandomization)

 

+ (NSArray *)randomArrayFromArray:(NSArray *)sortedArray;

 

@end

 

#import "NSArray+DERandomization.h"

@implementation NSArray (DERandomization)

 

+ (NSArray *)randomArrayFromArray:(NSArray *)sortedArray {

NSMutableArray *toRandomize = [sortedArray mutableCopy];

NSMutableArray *randomArray = [[[NSMutableArray alloc] init] autorelease];

NSUInteger arraySize = toRandomize.count;

NSUInteger randomIndex;

while(arraySize > 0) {

//Grab a random object from toRandomize and place it in first index of randomArray

randomIndex = arc4random() % arraySize;

[randomArray insertObject:[toRandomize objectAtIndex:randomIndex] atIndex:0];

[toRandomize removeObjectAtIndex:randomIndex];

arraySize = toRandomize.count;

}

[toRandomize release];

return randomArray;

}

 

@end

posted @ 2010-02-08 15:35  javawebsoa  Views(123)  Comments(0Edit  收藏  举报