What's the Best Way to Shuffle an NSMutableArray?

后端 未结 12 1708
太阳男子
太阳男子 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:03

    I solved this by adding a category to NSMutableArray.

    Edit: Removed unnecessary method thanks to answer by Ladd.

    Edit: Changed (arc4random() % nElements) to arc4random_uniform(nElements) thanks to answer by Gregory Goltsov and comments by miho and blahdiblah

    Edit: Loop improvement, thanks to comment by Ron

    Edit: Added check that array is not empty, thanks to comment by Mahesh Agrawal

    //  NSMutableArray_Shuffling.h
    
    #if TARGET_OS_IPHONE
    #import 
    #else
    #include 
    #endif
    
    // This category enhances NSMutableArray by providing
    // methods to randomly shuffle the elements.
    @interface NSMutableArray (Shuffling)
    - (void)shuffle;
    @end
    
    
    //  NSMutableArray_Shuffling.m
    
    #import "NSMutableArray_Shuffling.h"
    
    @implementation NSMutableArray (Shuffling)
    
    - (void)shuffle
    {
        NSUInteger count = [self count];
        if (count <= 1) return;
        for (NSUInteger i = 0; i < count - 1; ++i) {
            NSInteger remainingCount = count - i;
            NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
            [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
        }
    }
    
    @end
    

提交回复
热议问题