Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize an NSMutableArray? [duplicate]

Possible Duplicate:
iphone - nsarray/nsmutablearray - re-arrange in random order

I have an NSMutableArray that contains 20 objects. Is there any way that I could randomize their order like when you shuffle a deck. (By order I mean their index in the array)

Like if I had an array that contained:

  1. apple
  2. orange
  3. pear
  4. banana

How could I randomize the order so that I could get something like:

  1. orange
  2. apple
  3. banana
  4. pear
like image 376
Blane Townsend Avatar asked Dec 01 '22 08:12

Blane Townsend


1 Answers

Here's some sample code: Iterates through the array, and randomly switches an object's position with another.

for (int x = 0; x < [array count]; x++) {
    int randInt = (arc4random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
like image 140
Daniel Amitay Avatar answered Dec 04 '22 07:12

Daniel Amitay