gpt4 book ai didi

arrays - 使用 random() [Swift, Linux] 打乱字符串数组

转载 作者:可可西里 更新时间:2023-11-01 01:11:02 26 4
gpt4 key购买 nike

我正在尝试使用 Glibc 的 randr 函数在 linux 中替换 arc4random。尽管我设法打乱了一个整数数组,但我未能对一个字符串数组进行打乱。

下面的代码按预期工作:

import Foundation

extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }

for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount) + 1 ))
let i = index(firstUnshuffled, offsetBy: d)
swapAt(firstUnshuffled, i)
}
}
}

extension Sequence {
/// Returns an array with the contents of this sequence, shuffled.
func shuffled() -> [Element] {
var result = Array(self)
result.shuffle()
return result
}
}

let x = [1, 2, 3].shuffled()
print(x)
// [3, 1, 2]

但是如果我对一个字符串数组做同样的事情:

let fiveStrings = ["20", "45", "70", "30"].map(String.init).shuffled()
print(fiveStrings)

失败,索引超出范围。错误与

相同
var numbers = [1, 2, 3, 4]
print(numbers.shuffle())
  • 如何使用 random() 打乱字符串?

最佳答案

代码

 let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))

How do I shuffle an array in Swift?在中创建一个随机数在 0unshuffledCount-1 之间。为了达到同样的目的random() 使用

 let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount)))

没有 +1

请注意,与 arc4random_uniform() 相比:

关于arrays - 使用 random() [Swift, Linux] 打乱字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com