以与Swift相同的方式随机化两个数组

时间:2015-09-22 21:08:28

标签: swift

我知道有一个新的shuffle方法 iOS 9 但我想知道是否还有以同样的方式洗牌两个阵列?

例如

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

4 个答案:

答案 0 :(得分:5)

使用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] }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我没有意识到Swift 2.0中的任何内置shuffle机制。假设这不存在,我借用了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个数组,但修改它可以很容易。

答案 3 :(得分:0)

根据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)
""")

希望它有所帮助^ _________ ^。