What's the Best Way to Shuffle an NSMutableArray?

后端 未结 12 1685
太阳男子
太阳男子 2020-11-21 11:53

If you have an NSMutableArray, how do you shuffle the elements randomly?

(I have my own answer for this, which is posted below, but I\'m new to Cocoa an

12条回答
  •  情书的邮戳
    2020-11-21 12:24

    Since I can't yet comment, I thought I'd contribute a full response. I modified Kristopher Johnson's implementation for my project in a number of ways (really trying to make it as concise as possible), one of them being arc4random_uniform() because it avoids modulo bias.

    // NSMutableArray+Shuffling.h
    #import 
    
    /** This category enhances NSMutableArray by providing methods to randomly
     * shuffle the elements using the Fisher-Yates algorithm.
     */
    @interface NSMutableArray (Shuffling)
    - (void)shuffle;
    @end
    
    // NSMutableArray+Shuffling.m
    #import "NSMutableArray+Shuffling.h"
    
    @implementation NSMutableArray (Shuffling)
    
    - (void)shuffle
    {
        NSUInteger count = [self count];
        for (uint i = 0; i < count - 1; ++i)
        {
            // Select a random element between i and end of array to swap with.
            int nElements = count - i;
            int n = arc4random_uniform(nElements) + i;
            [self exchangeObjectAtIndex:i withObjectAtIndex:n];
        }
    }
    
    @end
    

提交回复
热议问题