0

Possible Duplicate:
What's the Best Way to Shuffle an NSMutableArray?

I have some values in a NSMutableArray. Now i need to shuffle these values. Can someone tell me how to shuffle these values.

Sorry i don't have any code to demonstrate.

I went through this SO post, which suggest to use exchangeObjectAtIndex:withObjectAtIndex:, but can someone show me how it is done. An example or a tutorial which explains this would help.

Community
  • 1
  • 1
Illep
  • 16,375
  • 46
  • 171
  • 302
  • 1
    Why didn't you look at the other answers for that question?? [One of them](http://stackoverflow.com/a/56656/689356) provides a complete solution. – yuji Apr 01 '12 at 15:50

1 Answers1

1

You can do it like this:

for (int i = [array count] - 1; i > 0; i--) {
    int j = arc4random() % (i+1);
    [array exchangeObjectAtIndex:i withObjectAtIndex:j];
}

array is Your NSMutableArray.

Justin Boo
  • 10,132
  • 8
  • 50
  • 71
  • For a good shuffle, you don't want to mod with `array count` but with `i`. See [the Fisher-Yates shuffle‌​](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm). – SSteve Apr 01 '12 at 16:13