简体   繁体   中英

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:

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:

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%?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM