如何规范加权列表?

时间:2015-04-20 09:25:04

标签: javascript weighted-average

我想加权元素列表并从列表中选择随机元素。我有以下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);

用户可以将权重指定为1到100之间的数字。输入将是这样的:

var list = ['javascript', 'php', 'ruby', 'python'];
var weight = [10, 50, 70, 90];

如何自定义Algorithmus,结尾的权重列表总和为100,每个元素的比例是否为100%?

1 个答案:

答案 0 :(得分:2)

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; });