我想建模一个函数,它会返回一组带有加权概率的值。像这样:
25% => return "a"
25% => return "b"
50% => return "c"
到目前为止,我见过的大部分文档都很重,很快就钻研了科学深度而没有例子,因此问题是: 实现这一目标的最简单方法是什么?
编辑:我正在使用Gatling DSL编写带有权重操作的负载测试。内置的权重分布有一个限制(不会在循环中工作),我想通过拥有自己的实现来避免。该片段如下所示:
override def scenarioBuilder = scenario(getClass.getSimpleName)
.exec(Account.create)
.exec(Account.login)
.exec(Account.activate)
.exec(Loop.create)
.forever(getAction)
def getAction = {
// Here is where I lost my wits
// 27.6% => Log.putEvents
// 18.2% => Log.putBinary
// 17.1% => Loop.list
// 14.8% => Key.listIncomingRequests
// rest => Account.get
}
答案 0 :(得分:2)
这是基于概率选择的通用函数的最短版本:
Test array - [1,2,3]
Numbers collection - [{value: 1}, {value: 3}]
Result should be - [1,3]
val probabilityMap = List(0.25 -> "a", 0.25 -> "b")
val otherwise = "c"
def getWithProbability[T](probs: List[(Double, T)], otherwise: T): T = {
// some input validations:
assert(probs.map(_._1).sum <= 1.0)
assert(probs.map(_._1).forall(_ > 0))
// get random in (0, 1) range
val rand = Random.nextDouble()
// choose by probability:
probs.foldLeft((rand, otherwise)) {
case ((r, _), (prob, value)) if prob > r => (1.0, value)
case ((r, result), (prob, _)) => (r-prob, result)
}._2
}
继续推进概率,直到找到foldLeft
更小的概率;如果我们还没有找到它,我们会转到下一个概率r
到&#34;删除&#34;我们已经涵盖的范围的一部分。
编辑:等同但可能更易于阅读的版本可以使用r-prob
创建累积范围,然后再搜索&#34;对于scanLeft
已降落的范围:
rand
答案 1 :(得分:0)
在那里,干净并准备好了:
randomSwitchOrElse(
27.6 -> exec(Log.putEvents),
18.2 -> exec(Log.putBinary))