How to randomize NSMutableArray?

Possible duplicate:
iphone - nsarray / nsmutablearray - sort in random order

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

As if I had an array containing:

  • an Apple
  • Orange
  • pear
  • banana

How could I randomize the order to get something like:

  • Orange
  • an Apple
  • banana
  • pear
+4
source share
2 answers

Here is an example code: Iterates through an array and randomly switches the position of an object with another.

for (int x = 0; x < [array count]; x++) { int randInt = (arc4random() % ([array count] - x)) + x; [array exchangeObjectAtIndex:x withObjectAtIndex:randInt]; } 
+15
source
 @interface NSArray (Shuffling) - (NSArray *)shuffledArray; @end @implementation NSArray (Shuffling) - (NSArray *)shuffledArray { NSMutableArray *newArray = [[self mutableCopy] autorelease]; [newArray shuffle]; return newArray; } @end @interface NSMutableArray (Shuffling) - (void)shuffle; @end @implementation NSMutableArray (Shuffling) - (void)shuffle { @synchronized(self) { NSUInteger count = [self count]; if (count == 0) { return; } for (NSUInteger i = 0; i < count; i++) { NSUInteger j = arc4random() % (count - 1); if (j != i) { [self exchangeObjectAtIndex:i withObjectAtIndex:j]; } } } } @end 

However, keep in mind that such a shuffle is just a pseudo-random shuffle !

+4
source

All Articles