Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-arrange NSArray/MSMutableArray in random order

Tags:

random

iphone

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?

like image 838
Satyam Avatar asked Nov 17 '10 06:11

Satyam


People also ask

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is NSMutableArray ordered?

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...

What is NSMutableArray in objective c?

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 .

Can NSArray contain nil?

arrays can't contain nil.


3 Answers

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];
}
like image 125
Nevin Avatar answered Oct 21 '22 22:10

Nevin


// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
    [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
like image 45
jwwatts Avatar answered Oct 21 '22 22:10

jwwatts


Link GameplayKit/GameplayKit.h in your project then

#import <GameplayKit/GameplayKit.h>

Now you can use the property shuffledArray.

NSArray *randomArray = [yourArray shuffledArray];
like image 36
John Franke Avatar answered Oct 21 '22 22:10

John Franke