【问题标题】:How do I shuffle multiple arrays using the same new indexes for each? [duplicate]如何使用相同的新索引对多个数组进行洗牌? [复制]
【发布时间】:2015-12-18 07:16:15
【问题描述】:

我有一系列书名,还有一个有相应的书名。让我们假设我需要它们在单独的数组中,而不是在同一个字典中。如何重新排序两个数组的索引,同时确保数组 2 的索引仍然对应于数组 1 的索引?

//This is what I currently have:
var arrayOne = ["one", "two", "three", "four"]
var arrayTwo = [1, 2, 3, 4]

//The new indexes should be random, non-repeating integers
arrayOne = ["four", "two", "three", "one"]
arrayTwo = [4, 2, 3, 1]

【问题讨论】:

  • edit您的帖子显示您为解决此问题而编写的一些代码
  • @SunilChauhan 因为我希望新订单是随机的

标签: ios arrays swift


【解决方案1】:

此代码在 Swift 2.0 上测试

    extension CollectionType {
    /// 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 arr1 = [1, 2, 3, 4]
let arr2 = ["a", "b", "c", "d"]

var shuffled_ind = arr1.indices.shuffle()

let shuffled_arr1 = Array(PermutationGenerator(elements: arr1, indices: shuffled_ind))
let shuffled_arr2 = Array(PermutationGenerator(elements: arr2, indices: shuffled_ind))

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

这是输出

参考了这两个帖子并使用了它们的扩展

How do I shuffle an array in Swift?

How can I sort multiple arrays based on the sorted order of another array3

Randomize two arrays the same way Swift

【讨论】:

  • indices 没有名为 shuffle() 的成员?
  • 我也不想排序。我希望新索引是随机的、不重复的整数
  • 我已经更新了代码并且是随机的
  • 如果你觉得我的回答有用,别忘了点赞并接受:)
猜你喜欢
  • 2016-02-09
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 2021-12-17
  • 2015-04-10
  • 2013-01-14
相关资源
最近更新 更多