Re-arrange NSArray/MSMutableArray in random order

后端 未结 4 1420
余生分开走
余生分开走 2020-12-01 11:32

I\'m using NSArray/NSMutable array to store different objects. Once all the objects are added, I want to re-arrange them in random order. How can I do it?

相关标签:
4条回答
  • 2020-12-01 11:39

    Swift 4

    let count = self.arrayOfData.count
    for (index, _) in self.arrayOfData.enumerated()
    {
      let nTempElement = count - index
      let swapIndexwith = (Int(arc4random()) % nTempElement) + index
      arrayOfData.swapAt(index, swapIndexwith)
    }
    
    0 讨论(0)
  • 2020-12-01 11:45
    // the Knuth shuffle
    for (NSInteger i = array.count-1; i > 0; i--)
    {
        [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
    }
    
    0 讨论(0)
  • 2020-12-01 11:46
    NSUInteger count = [yourMutableArray count];
    for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
       int nElements = count - i;
       int n = (arc4random() % nElements) + i;
       [yourMutableArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    
    0 讨论(0)
  • 2020-12-01 11:50

    Link GameplayKit/GameplayKit.h in your project then

    #import <GameplayKit/GameplayKit.h>
    

    Now you can use the property shuffledArray.

    NSArray *randomArray = [yourArray shuffledArray];
    
    0 讨论(0)
提交回复
热议问题