How to normalize a weighted list?

I would like to weigh a list of items and select a random item from the list. I have the following javascript that does it:

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 enter the weight as a number between 1 and 100. The input would be something like this:

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

      

How to tune the Algorithm, since the sum of the weight list at the end is 100, and each element has the correct ratio up to 100%?

+3


source to share


1 answer


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

      



+2


source







All Articles