我试图使用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)
它以Index out of range
失败。
var numbers = [1, 2, 3, 4]
print(numbers.shuffle())
答案 0 :(得分:2)
代码
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?。