How to randomize an NSMutableArray? [duplicate]

不问归期 提交于 2019-12-01 08:33:12

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

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