【问题标题】:Randomize two arrays the same way Swift以 Swift 相同的方式随机化两个数组
【发布时间】:2015-09-22 21:08:27
【问题描述】:

我知道 iOS 9 有一种新的随机播放方法 但我想知道是否有办法以同样的方式洗牌两个数组?

例如

[1,2,3,4] and [a,b,c,d]
shuffle
[3,4,1,2] and [c,d,a,b]

【问题讨论】:

  • 你指的是 iOS 9 中哪种新的 shuffle 方法?

标签: swift


【解决方案1】:

使用来自How do I shuffle an array in Swift?shuffle() 方法和来自How can I sort multiple arrays based on the sorted order of another array 的想法 您可以对数组 indices 进行洗牌,然后对两者(或更多)重新排序 相应的数组:

let a = [1, 2, 3, 4]
let b = ["a", "b", "c", "d"]

var shuffled_indices = a.indices.shuffle()

let shuffled_a = Array(PermutationGenerator(elements: a, indices: shuffled_indices))
let shuffled_b = Array(PermutationGenerator(elements: b, indices: shuffled_indices))

print(shuffled_a) // [3, 1, 2, 4]
print(shuffled_b) // ["c", "a", "b", "d"]

Swift 3 (Xcode 8) 更新: PermutationGenerator 没有 Swift 3 中不再存在。 使用shuffled() 方法 来自Shuffle array swift 3 也可以使用

var shuffled_indices = a.indices.shuffled()

let shuffled_a = shuffled_indices.map { a[$0] }
let shuffled_b = shuffled_indices.map { b[$0] }

【讨论】:

    【解决方案2】:

    使用字典临时存储值,随机排列键,然后通过从字典中提取值来重建另一个数组。

    【讨论】:

      【解决方案3】:

      我不知道 Swift 2.0 中有任何内置的随机播放机制。假设这不存在,我从here借了一些代码。

      extension CollectionType where Index == Int {
          /// Return a copy of `self` with its elements shuffled
          func shuffle() -> [Generator.Element] {
              var list = Array(self)
              list.shuffleInPlace()
              return list
          }
      }
      
      extension MutableCollectionType where Index == Int {
          /// Shuffle the elements of `self` in-place.
          mutating func shuffleInPlace() {
              // empty and single-element collections don't shuffle
              if count < 2 { return }
      
              for i in 0..<count - 1 {
                  let j = Int(arc4random_uniform(UInt32(count - i))) + i
                  guard i != j else { continue }
                  swap(&self[i], &self[j])
              }
          }
      }
      
      let shuffleOrder = [0,1,2,3]
      let shuffled = shuffleOrder.shuffle()
      
      
      var newArray1 = [String]()
      var newArray2 = [String]()
      
      let array1 = ["a", "b", "c", "d"]
      let array2 = ["w", "x", "y", "z"]
      
      
      shuffled.forEach() { index in
          newArray1.append(array1[index])
          newArray2.append(array2[index])
      }
      

      这以非常直接的方式解决了问题。它创建了一个数组shuffleOrder,它只为起始数组中的每个可能的索引提供了一个索引。然后它打乱这些索引以创建随机抽样顺序。最后,它基于起始数组构造两个新数组,并使用shuffled 值对它们进行采样。虽然这不会改变原来的 2 个数组,但修改它会很简单。

      【讨论】:

        【解决方案4】:

        根据 Martin R 的原始答案,您可以使用 GameKit 解决问题。

        答案是用 Swift4 写的:

        var arrayA = [1, 2, 3, 4]
        var arrayB = ["a", "b", "c", "d"]
        
        //Get The Indices Of The 1st Array 
        var shuffledIndices: [Int] = Array(arrayA.indices)
        print("Shuffled Indices = \(shuffledIndices)")
        
        //Shuffle These Using GameKit
        shuffledIndices = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: shuffledIndices) as! [Int]
        
        //Map The Objects To The Shuffled Indices
        arrayA = shuffledIndices.map { arrayA[$0] }
        arrayB = shuffledIndices.map { arrayB[$0] }
        
        //Log The Results
        print("""
        Array A = \(arrayA)
        Array B = \(arrayB)
        """)
        

        希望对您有所帮助^_________^。

        【讨论】:

          猜你喜欢
          • 2011-05-12
          • 2021-04-26
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          • 1970-01-01
          • 2020-12-10
          • 1970-01-01
          相关资源
          最近更新 更多