代码之家  ›  专栏  ›  技术社区  ›  Satyam

按随机顺序重新排列nsarray/msmutablearray

  •  14
  • Satyam  · 技术社区  · 14 年前

    我正在使用nsarray/nsmutable数组存储不同的对象。 一旦所有的对象都被添加了,我想以随机的顺序重新排列它们。 我该怎么做?

    4 回复  |  直到 14 年前
        1
  •  55
  •   Nevin    14 年前
    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];
    }
    
        2
  •  25
  •   jwwatts    12 年前
    // the Knuth shuffle
    for (NSInteger i = array.count-1; i > 0; i--)
    {
        [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
    }
    
        3
  •  0
  •   John Franke    6 年前

    在项目中链接gameplaykit/gameplaykit.h,然后

    #import <GameplayKit/GameplayKit.h>
    

    现在可以使用shuffedray属性。

    NSArray *randomArray = [yourArray shuffledArray];
    
        4
  •  0
  •   Nimesh    6 年前

    斯威夫特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)
    }