从数组中选择随机加权对象

时间:2019-03-20 09:05:02

标签: javascript arrays object weighted

我正在尝试根据权重属性从数组中选择随机对象的方法。这是一个示例数组:

var item = [{
    verDiv: 'div-gpt-ad-1553003087342-0',
    verKv: 'version1',
    verSize: [300, 250],
    weight: 10 //should be chosen in 10% of cases
},
{
    verDiv: 'div-gpt-ad-1553003087342-1',
    verKv: 'version2',
    verSize: [300, 250],
    weight: 25 //should be chosen in 25% of cases
},
{
    verDiv: 'div-gpt-ad-1553003087342-2',
    verKv: 'version3',
    verSize: [160, 600],
    weight: 25 //should be chosen in 25% of cases
},
{
    verDiv: 'div-gpt-ad-1553003087342-3',
    verKv: 'version4',
    verSize: [728, 90],
    weight: 40 //should be chosen in 40% of cases
}];

我想做的是使用一个函数选择四个对象之一,该函数考虑了它们的权重属性,因此我可以在需要时调用其他属性。

console.log([item[weightFunction()].verDiv]);
console.log([item[weightFunction()].verKv]);
console.log([item[weightFunction()].verSize]);

编辑:以上仅是一个建议,我相信还有更好的方法。

4 个答案:

答案 0 :(得分:1)

假设所有权重的总和正好是100(否则将其计算并用作cumul初始值和随机乘数:

function weightFunction(items) {
  var cumul = 100
  var random = Math.floor(Math.random() * 100)

  for(var i = 0; i < items.length; i++) {
    cumul -= items[i].weight
    if (random >= cumul) {
      return items[i]
    }
  }
}

答案 1 :(得分:1)

您可以对所有权重的权重数组进行闭包,然后返回一个函数,该函数根据所有权重的总和获取索引。

function getWeightedDistribution(weights) {
    return function () {
        var random = Math.random(),
            sum = 0;
        return weights.findIndex(w => random < (sum += w));
    };
}

var weights = [0.1, 0.25, 0.25, 0.4], // all values have to sum to 1
    i;
    weightFunction = getWeightedDistribution(weights),
    counts = [0, 0, 0, 0];

for (i = 0; i < 1e6; i++) counts[weightFunction()]++;

console.log(...counts);

与您的代码一起

function getWeightedDistribution(weights) { // weights sums up to 1
    return function () {
        var random = Math.random(),
            sum = 0;
        return weights.findIndex(w => random < (sum += w));
    };
}

var item = [{ verDiv: 'div-gpt-ad-1553003087342-0', verKv: 'version1', verSize: [300, 250], weight: 10 }, { verDiv: 'div-gpt-ad-1553003087342-1', verKv: 'version2', verSize: [300, 250], weight: 25 }, { verDiv: 'div-gpt-ad-1553003087342-2', verKv: 'version3', verSize: [160, 600], weight: 25 }, { verDiv: 'div-gpt-ad-1553003087342-3', verKv: 'version4', verSize: [728, 90], weight: 40 }],
    weightFunction = getWeightedDistribution(item.map(({ weight }) => weight / 100));

console.log(item[weightFunction()].verDiv);
console.log(item[weightFunction()].verKv);
console.log(item[weightFunction()].verSize);

答案 2 :(得分:0)

这是解决该问题的一种更抽象的方法,它允许总权重大于100,并且您可以定义如何检索每个元素的weight属性。

此方法的工作方式是为每个值创建一个范围映射,并返回范围“捕获”随机数的第一个元素。

var item = [{
    verDiv: 'div-gpt-ad-1553003087342-0',
    verKv: 'version1',
    verSize: [300, 250],
    weight: 10 //should be chosen in 10% of cases
  },
  {
    verDiv: 'div-gpt-ad-1553003087342-1',
    verKv: 'version2',
    verSize: [300, 250],
    weight: 25 //should be chosen in 25% of cases
  },
  {
    verDiv: 'div-gpt-ad-1553003087342-2',
    verKv: 'version3',
    verSize: [160, 600],
    weight: 25 //should be chosen in 25% of cases
  },
  {
    verDiv: 'div-gpt-ad-1553003087342-3',
    verKv: 'version4',
    verSize: [728, 90],
    weight: 40 //should be chosen in 40% of cases
  }
];

function weightFunction(list, getWeight) {
  var total = 0; // Faster than doing another loop with reduce
  var map = list.reduce(function(result, value, index) {
    var currentWeight = getWeight(value, index);
    total += currentWeight;
    result[total] = value;
    return result;
  }, {});
  var random = Math.random() * total;
  return map[Object.keys(map).find(function(index) {
    return index >= random;
  })];
}

console.log(weightFunction(item, x => x.weight).verDiv);
console.log(weightFunction(item, x => x.weight).verKv);
console.log(weightFunction(item, x => x.weight).verSize);

答案 3 :(得分:0)

  • 定义一个名为stat_map的数组,该数组最终的大小为sum of all weights
  • 用商品索引填充stat_map,以便stat_map包含与商品重量相同的商品索引。
  • 现在stat_map包含10 0(第一项索引),25 1(第二项索引),25 2(第三项索引),40 {{1} }(第四项的索引)
  • 如果您从stat_map中选择随机元素,它将是所选项目的索引,很明显,将根据其重量来选择项目。

3