[英]How to normalize weighted list?
I would like to weight a list of elements and select random element from the list. 我想加权一个元素列表,并从列表中选择随机元素。 I have the following javascript, which do that: 我有以下javascript,这样做:
var generateWeighedList = function(list, weight) {
var weighed_list = [];
// Loop over weights
for (var i = 0; i < weight.length; i++) {
var multiples = weight[i] * 100;
// Loop over the list of items
for (var j = 0; j < multiples; j++) {
weighed_list.push(list[i]);
}
}
return weighed_list;
};
var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [0.5, 0.2, 0.2, 0.1];
var weighed_list = generateWeighedList(list, weight);
console.log(weighed_list.length);
The User can give the weight as number between 1 and 100. The input will be something like this: 用户可以将权重指定为1到100之间的数字。输入将是这样的:
var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [10, 50, 70, 90];
How to customize the Algorithmus, sothat the sum of the weight list at the end is 100 and every element has the right ratio to 100%? 如何自定义Algorithmus,结果权重列表的总和为100,每个元素的比例是否为100%?
var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [10, 50, 70, 90];
// build new array with length of weight
var weighed_list = Array.apply(null, { length: weight.length });
// get the sum of all weights
var sum = weight.reduce(function (a, b) { return a + b; }, 0);
// final take the ratio of every weight
weight.forEach(function (a, i) { weighed_list[i] = 100 * a / sum; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.