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?

10 thoughts on “Objective-C – How to Shuffle a NSMutableArray”

  1. I applied the same but i get the error–

    *** Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘*** -[NSMutableArray objectAtIndex:]: index 4294967295 beyond bounds [0 .. 26]’

    Like

    1. how do u create the mutable array? a nil is needed for the last item.
      For examplp:

      NSMutableArray *a = [NSMutableArray arrayWithObjects:@"Cat", @"Dog", @"Fish", @"Squirrel", @"Bear", @"Turtle", nil];
      

      Like

  2. Thanks for this tutorial and I find it useful, although this code srandom(time(NULL)); is not necessary so we can remove it. And we should also use arc4random() instead of random(). Anyway, thanks for this!

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.