[英]Fastest weighted random algorithm in Scala?
我正在为基于 Scala 的项目编写服务器端模块,我需要找到在某些Int
权重之间执行加权随机数生成的最快方法。 该方法应该尽可能快,因为它会被经常调用。
现在,这就是我想出的:
import scala.util.Random
trait CumulativeDensity {
/** Returns the index result of a binary search to find @n in the discrete
* @cdf array.
*/
def search(n: Int, cdf: Array[Int]): Int = {
val i: Int = cdf.indexWhere(_ != 0)
if (i<0 | n<=cdf(i))
i
else
search(n-cdf(i), {cdf.update(i,0); cdf})
}
/** Returns the cumulative density function (CDF) of @list (in simple terms,
* the cumulative sums of the weights).
*/
def cdf(list: Array[Int]) = list.map{
var s = 0;
d => {s += d; s}
}
}
我用这段代码定义了 main 方法:
def rndWeighted(list: Array[Int]): Int =
search(Random.nextInt(list.sum + 1), cdf(list))
但是,它仍然不够快。 从列表开始(库、内置函数、启发式算法)开始,是否有任何一种黑魔法使得没有必要对其进行迭代?
编辑:这是代码的最终版本(现在快得多):
def search(n: Int, cdf: Array[Int]): Int = {
if (n > cdf.head)
1 + search(n-cdf.head, cdf.tail)
else
0
}
而不是cdf.update(i,0)
并将整个cdf
传递回cdf.indexWhere(_ != 0)
在下一次递归调用中,请考虑
cdf.splitAt(i)
并且仅传递i
右侧的元素,因此在以下递归中, indexWhere
扫描较小的数组。 请注意,数组大小在每次递归调用时单调递减,以确保终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.