Tag Archives: NSMutableArray

Objective-C – How to Shuffle a NSMutableArray

You can use the following piece of code to randomize/shuffle the objects inside a NSMutableArray.

/* anArray is a NSMutableArray with some objects */
srandom(time(NULL));
NSUInteger count = [anArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (random() % nElements) + i;
	[anArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

 

Update @ 2012-07-18: Suggestion from kimbebot

/* anArray is a NSMutableArray with some objects */
NSUInteger count = [anArray count];
for (NSUInteger i = 0; i < count; ++i) {
	int nElements = count - i;
	int n = (arc4random() % nElements) + i;
	[anArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

Done =)

Reference: StackOverflow – What’s the Best Way to Shuffle an NSMutableArray?