I'm using NSArray/NSMutable array to store different objects. Once all the objects are added, I want to re-arrange them in random order. How can I do it?
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .
arrays can't contain nil.
NSUInteger count = [yourMutableArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[yourMutableArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}
// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
[array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
Link GameplayKit/GameplayKit.h in your project then
#import <GameplayKit/GameplayKit.h>
Now you can use the property shuffledArray.
NSArray *randomArray = [yourArray shuffledArray];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With