Possible Duplicate:
iphone - nsarray/nsmutablearray - re-arrange in random order
I have an NSMutableArray that contains 20 objects. Is there any way that I could randomize their order like when you shuffle a deck. (By order I mean their index in the array)
Like if I had an array that contained:
- apple
- orange
- pear
- banana
How could I randomize the order so that I could get something like:
- orange
- apple
- banana
- pear
Here's some sample code: Iterates through the array, and randomly switches an object's position with another.
for (int x = 0; x < [array count]; x++) {
int randInt = (arc4random() % ([array count] - x)) + x;
[array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
@interface NSArray (Shuffling)
- (NSArray *)shuffledArray;
@end
@implementation NSArray (Shuffling)
- (NSArray *)shuffledArray {
NSMutableArray *newArray = [[self mutableCopy] autorelease];
[newArray shuffle];
return newArray;
}
@end
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
@implementation NSMutableArray (Shuffling)
- (void)shuffle {
@synchronized(self) {
NSUInteger count = [self count];
if (count == 0) {
return;
}
for (NSUInteger i = 0; i < count; i++) {
NSUInteger j = arc4random() % (count - 1);
if (j != i) {
[self exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
}
@end
However keep in mind that this kind of shuffling is merely pseudorandom shuffling!
来源:https://stackoverflow.com/questions/6255369/how-to-randomize-an-nsmutablearray