4

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
Community
  • 1
  • 1
Blane Townsend
  • 2,888
  • 5
  • 41
  • 55

2 Answers2

16

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];
}
Daniel Amitay
  • 6,677
  • 7
  • 36
  • 43
4
@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 this kind of shuffling is merely pseudorandom shuffling!

Regexident
  • 29,441
  • 10
  • 93
  • 100