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?

About these ads

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

  1. alan

    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]‘

    Reply
    1. ykyuen Post author

      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];
      
      Reply
  2. kimbebot

    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!

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s