You can copy the array into NSMutableArray and shuffle it. A simple demonstration of how to mix an array:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Original array, here initialised with 1..9 NSArray *arr = [NSArray arrayWithObjects: [NSNumber numberWithInt: 1], [NSNumber numberWithInt: 2], [NSNumber numberWithInt: 3], [NSNumber numberWithInt: 4], [NSNumber numberWithInt: 5], [NSNumber numberWithInt: 6], [NSNumber numberWithInt: 7], [NSNumber numberWithInt: 8], [NSNumber numberWithInt: 9], nil]; // Array that will be shuffled NSMutableArray *shuffled = [NSMutableArray arrayWithArray: arr]; // Shuffle array for (NSUInteger i = shuffled.count - 1; i > 0; i--) { NSUInteger index = rand() % i; NSNumber *temp = [shuffled objectAtIndex: index]; [shuffled removeObjectAtIndex: index]; NSNumber *top = [shuffled lastObject]; [shuffled removeLastObject]; [shuffled insertObject: top atIndex: index]; [shuffled addObject: temp]; } // Display shuffled array for (NSNumber *num in shuffled) { NSLog(@"%@", num); } [pool drain]; return 0; }
Note that all arrays and numbers here are auto-implemented, but in your code you may need memory management.
If you don't need to store elements in an array, you can simplify this (see also Oscar Gomez answer):
NSUInteger index = rand() % shuffled.count; NSLog(@"%@", [shuffled objectAtIndex: index]); [shuffled removeObjectAtIndex: index];
In the end, the shuffled will be empty. You will also have to change the conditions of the loop:
for (NSUInteger i = 0; i < shuffled.count; i++)
Rudy velthuis
source share