【问题标题】:Replacing objects in one array to another array, randomly. Swift 4将一个数组中的对象随机替换为另一个数组。斯威夫特 4
【发布时间】:2018-12-24 10:28:33
【问题描述】:

两个数组

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

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

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

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

我想随机做这个,例如

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

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

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

所以我似乎被困住了。 BTW 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。

【问题讨论】:

  • 试试这个: let randomNumber: Int = Int(arc4random()) % (array2.count) ; array2.insert(array1[randomNumber], at: randomNumber)

标签: arrays swift for-loop random set


【解决方案1】:

这看起来效率很低,但很有效:

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"]

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

【讨论】:

    【解决方案2】:

    您需要随机索引吗?如果是这样,下面的代码就可以了。

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

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

    【讨论】:

    • 我想到了 shuffled(),但我需要它们不要被洗牌。他们需要保持秩序。谢谢
    【解决方案3】:
         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)")
    

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多