gpt4 book ai didi

javascript - 如何标准化加权列表?

转载 作者:行者123 更新时间:2023-11-29 14:48:20 25 4
gpt4 key购买 nike

我想对元素列表进行加权并从列表中选择随机元素。我有以下 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%?

最佳答案

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

关于javascript - 如何标准化加权列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29743923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com