What's the Best Way to Shuffle an NSMutableArray?

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

    Kristopher Johnson's answer is pretty nice, but it's not totally random.

    Given an array of 2 elements, this function returns always the inversed array, because you are generating the range of your random over the rest of the indexes. A more accurate shuffle() function would be like

    - (void)shuffle
    {
       NSUInteger count = [self count];
       for (NSUInteger i = 0; i < count; ++i) {
           NSInteger exchangeIndex = arc4random_uniform(count);
           if (i != exchangeIndex) {
                [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
           }
       }
    }
    

提交回复
热议问题