我有一个像这样的对象:
{
"user1": 200,
"user2": 50,
"user3": 250,
"user4": 100
}
我想根据与其属性相关联的值随机选择其中一个用户。所以在这种情况下,user1应该有33.33%的获胜机会,user2应该有8.33%,依此类推。我怎么能这样做?
答案 0 :(得分:1)
你只需选择0到N之间的数字,其中N是所有权重的总和,然后找出权重所在的位置:
function selectByWeight(list) {
var total = 0;
Object.keys(list).forEach(function(k) {
total += list[k];
});
var selection = Math.random() * total;
var selected;
var count = 0;
Object.keys(list).forEach(function(k) {
count += list[k];
if (count > selection && !selected) {
selected = k;
}
});
return selected;
}
var users = {
"user1": 200,
"user2": 50,
"user3": 250,
"user4": 100
}
console.log(selectByWeight(users));