15

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Satyam
  • 15,493
  • 31
  • 131
  • 244

4 Answers4

55
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];
}
Nevin
  • 7,689
  • 1
  • 23
  • 25
27
// the Knuth shuffle
for (NSInteger i = array.count-1; i > 0; i--)
{
    [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
}
jwwatts
  • 271
  • 3
  • 2
  • Best solution if you target your app iOS >= 4.3. `__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3)` – Hemang Oct 22 '12 at 05:56
  • why do you iterate from n -> 0 and not 0 -> n – Peter Lapisu Dec 05 '14 at 23:38
  • @Peter He iterates backwards because he doesn't want to get the count at every iteration and the direction doesn't matter since we're randomizing it anyway. Keeps the line count down. – Robert Nall Jan 15 '15 at 02:16
1

Link GameplayKit/GameplayKit.h in your project then

#import <GameplayKit/GameplayKit.h>

Now you can use the property shuffledArray.

NSArray *randomArray = [yourArray shuffledArray];
John Franke
  • 1,444
  • 19
  • 23
0

Swift 4

let count = self.arrayOfData.count
for (index, _) in self.arrayOfData.enumerated()
{
  let nTempElement = count - index
  let swapIndexwith = (Int(arc4random()) % nTempElement) + index
  arrayOfData.swapAt(index, swapIndexwith)
}
nimesh surani
  • 177
  • 1
  • 13