看看这个问题:
Swift probability of random number being selected?
最佳答案建议使用 switch 语句来完成这项工作。但是,如果我要考虑的情况非常多,代码看起来就很不优雅;我有一个巨大的 switch 语句,在每种情况下都一遍又一遍地重复非常相似的代码。
当您需要考虑大量概率时,是否有更好、更简洁的方法来以一定的概率选择随机数? (大约 30 个)
最佳答案
这是一个 Swift 实现,深受各种 Generate random numbers with a given (numerical) distribution的答案.
对于 Swift 4.2/Xcode 10 及更高版本(内联解释):
func randomNumber(probabilities: [Double]) -> Int {
// Sum of all probabilities (so that we don't have to require that the sum is 1.0):
let sum = probabilities.reduce(0, +)
// Random number in the range 0.0 <= rnd < sum :
let rnd = Double.random(in: 0.0 ..< sum)
// Find the first interval of accumulated probabilities into which `rnd` falls:
var accum = 0.0
for (i, p) in probabilities.enumerated() {
accum += p
if rnd < accum {
return i
}
}
// This point might be reached due to floating point inaccuracies:
return (probabilities.count - 1)
}
例子:
let x = randomNumber(probabilities: [0.2, 0.3, 0.5])
以 0.2 的概率返回 0,以 0.3 的概率返回 1, 和 2,概率为 0.5。
let x = randomNumber(probabilities: [1.0, 2.0])
以 1/3 的概率返回 0,以 2/3 的概率返回 1。
对于 Swift 3/Xcode 8:
func randomNumber(probabilities: [Double]) -> Int {
// Sum of all probabilities (so that we don't have to require that the sum is 1.0):
let sum = probabilities.reduce(0, +)
// Random number in the range 0.0 <= rnd < sum :
let rnd = sum * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)
// Find the first interval of accumulated probabilities into which `rnd` falls:
var accum = 0.0
for (i, p) in probabilities.enumerated() {
accum += p
if rnd < accum {
return i
}
}
// This point might be reached due to floating point inaccuracies:
return (probabilities.count - 1)
}
对于 Swift 2/Xcode 7:
func randomNumber(probabilities probabilities: [Double]) -> Int {
// Sum of all probabilities (so that we don't have to require that the sum is 1.0):
let sum = probabilities.reduce(0, combine: +)
// Random number in the range 0.0 <= rnd < sum :
let rnd = sum * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)
// Find the first interval of accumulated probabilities into which `rnd` falls:
var accum = 0.0
for (i, p) in probabilities.enumerate() {
accum += p
if rnd < accum {
return i
}
}
// This point might be reached due to floating point inaccuracies:
return (probabilities.count - 1)
}
关于ios - 生成具有给定分布的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309556/