我正在尝试使用 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?在中创建一个随机数
在 0
和 unshuffledCount-1
之间。为了达到同样的目的
random()
使用
let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount)))
没有 +1
。
请注意,与 arc4random_uniform()
相比:
random()
必须播种,否则每次运行程序都会产生相同的结果 随机数序列。random() % upperBound
存在“模偏差”, 比较 Why do people say there is modulo bias when using a random number generator? .
关于arrays - 使用 random() [Swift, Linux] 打乱字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130559/