将一个数组中的对象随机替换为另一个数组。迅捷4

时间:2018-07-16 19:52:52

标签: arrays swift for-loop random set

两个数组

let array1 = ["A","B","C","D","E","F","G"]

let array2 = ["a","b","c","d","e","f","g"]

我想从array2中选择一个索引,并用与array2中的对象相同的索引替换array1中的对象。例如

array1[3] = array2[3] //["A","B","C","d","E","F","G"]

例如,我想随机执行

let randomIndex: Int = Int(arc4random()) % (array2.count)

我想在“ for”循环中执行此操作,直到使用了array2的所有索引和对象为止,但是我不想重复randomIndex。

如果每次迭代后减少对象数,我仍然可以获得相同的随机索引。如果我使用一组索引,然后删除使用的索引,我将失去“有序性”(如果这是一个词)。

所以我似乎被困住了。顺便说一句swift 4的.randomElement不适用于字符串数组。

有什么想法吗?

for object in array2 {

  let randomIndex: Int = Int(arc4random()) % (array2.count)
  array1[randomIndex] = array2[randomIndex]
  array2.remove(at: randomIndex)
  }

以上内容无法按我的期望进行。删除对象后,将建立新的顺序,并且无法在适当的索引处替换array1中的对象。

我缺少明显的东西,但是我没有看到。我正在使用Swift 4.2。

3 个答案:

答案 0 :(得分:0)

这似乎效率很低,但是可以起作用:

let array1 = ["A","B","C","D","E","F","G"]
let array2 = ["a","b","c","d","e","f","g"]
var array3 = array1                       // ["A","B","C","D","E","F","G"]
var counterSet = Set<Int>()               // empty set

while counterSet.count < array2.count {
  let randomIndex: Int = Int(arc4random()) % (array2.count)    //(16 times)
  counterSet.insert(randomIndex)                               //(16 times)
  array3[randomIndex] = array2[randomIndex]                    //(16 times)
}
counterSet                                // {2, 4, 6, 5, 0, 1, 3}
array3                                    // ["a", "b", "c", "d", "e", "f", "g"]

我仍然想要一些输入。谢谢库尔特

答案 1 :(得分:0)

您需要改组索引吗?如果是这样,则下面的代码可以执行此操作。

( 0 ..< array2.count ).shuffled()

Array( stride( from: 0, through: array2.count - 1, by: 1 ) ).shuffled()

答案 2 :(得分:0)

     var array1  = ["A","B","C","D","E","F","G"]

     var array2  = ["a","b","c","d","e","f","g"]

    let randomIndex: Int = Int(arc4random()) % (array2.count)
    print("Number:\(randomIndex)")

    array2.insert(array1[randomIndex], at: randomIndex)
    print("array2:\(array2)")