How to randomize an NSMutableArray? [duplicate]

≯℡__Kan透↙ 提交于 2019-12-01 05:11:06

问题


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

回答1:


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];
}



回答2:


@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!



来源:https://stackoverflow.com/questions/6255369/how-to-randomize-an-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!