Skip to content

Instantly share code, notes, and snippets.

@josephchang10
Created April 18, 2017 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephchang10/8b9e1b2ab1eb1e7c135dde96aec4c7c1 to your computer and use it in GitHub Desktop.
Save josephchang10/8b9e1b2ab1eb1e7c135dde96aec4c7c1 to your computer and use it in GitHub Desktop.
How to shuffle a NSMutableArray [Objective-C]
/* myArray is a NSMutableArray with some objects */
NSUInteger count = [myArray count];
for (NSUInteger i = 0; i < count; ++i) {
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[myArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
@josephchang10
Copy link
Author

The Objective-C NSArray object doesn’t have a specific function to shuffle the elements of the array.

With this simple code we can shuffle one NSMutableArray randomly. We will use the exchangeObjectAtIndex method for exchange items within the array and arc4random to get a random number we use to exchange items.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment