如何生成元素的随机加权分布 [英] How to generate a random weighted distribution of elements
问题描述
我想返回一个数组,该数组具有一组根据自定义频率随机分布的唯一元素。我在现实世界中的用例是根据图像的受欢迎程度的定性权重对轮播图像进行重复。
I would like to return an array which has a set of unique elements randomly distributed according to custom frequency. My real world use-case is the repetition of carousel images based on a qualitative weighting of how popular those images are.
例如假设我有5个权重元素:
E.g. suppose I have 5 elements with weights:
A,20%
B,50%
C,80%
D,10 %
A, 20% B, 50% C, 80% D, 10%
我想编写一个函数,该函数在给定长度的情况下试图近似一个序列,以使C出现的频率是D的八倍; D的出现频率比B少5倍; A的出现频率是C的三倍。
I would like to write a function that, given a length, tries to approximate a sequence such that C will appear eight times more often than D; D will appear 5 times less often than B; A will appear three times less often than C.
推荐答案
C的出现频率是C的八倍D; D的出现频率比B少5倍; A的出现频率比C少三倍。
C will appear eight times more often than D; D will appear 5 times less often than B; A will appear three times less often than C.
您可以使用元素的加权数组来做到这一点:
You can do that with a weighted array of your elements:
var elems = ["A", "B", "C", "D"];
var weights = [2, 5, 8, 1]; // weight of each element above
var totalWeight = weights.reduce(add, 0); // get total weight (in this case, 16)
function add(a, b) { return a + b; } // helper function
var weighedElems = [];
var currentElem = 0;
while (currentElem < elems.length) {
for (i = 0; i < weights[currentElem]; i++)
weighedElems[weighedElems.length] = elems[currentElem];
currentElem++;
}
console.log(weighedElems);
这将产生一个类似
的数组
[ A, A, B, B, B, B, B, C, C, C, C , C, C, C, C, D]
["A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C", "C", "C", "D"]
所以您可以随机选择
var rnd = Math.floor(Math.random() * totalWeight);
console.log(weighedElems[rnd]);
资源:
- Generate A Weighted Random Number
- Weighted random number generation in Javascript
- Algorithm for generating weighed random numbers
这篇关于如何生成元素的随机加权分布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!