Reputation: 2917
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%?
Upvotes: 3
Views: 784
Reputation: 386746
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; });
Upvotes: 4