【问题标题】:Re-arrange NSArray/MSMutableArray in random order以随机顺序重新排列 NSArray/NSMutableArray
【发布时间】:2010-11-17 06:42:48
【问题描述】:

我正在使用 NSArray/NSMutable 数组来存储不同的对象。 添加所有对象后,我想以随机顺序重新排列它们。 我该怎么做?

【问题讨论】:

    标签: iphone random


    【解决方案1】:
    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】:
      // the Knuth shuffle
      for (NSInteger i = array.count-1; i > 0; i--)
      {
          [array exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform(i+1)];
      }
      

      【讨论】:

      • 如果您的应用程序以 iOS >= 4.3 为目标,则为最佳解决方案。 __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3)
      • 你为什么从 n -> 0 迭代而不是 0 -> n
      • @Peter He 向后迭代,因为他不想在每次迭代时都获得计数,而且方向并不重要,因为我们无论如何都会对其进行随机化。保持行数倒计时。
      【解决方案3】:

      然后在您的项目中链接 GameplayKit/GameplayKit.h

      #import <GameplayKit/GameplayKit.h>
      

      现在您可以使用属性 shuffledArray。

      NSArray *randomArray = [yourArray shuffledArray];
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-03
          • 2012-11-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-03
          相关资源
          最近更新 更多