This question already has answers here:
Generate A Weighted Random Number
                                
                                    (11个答案)
                                
                        
                        
                            Get random element from array with weighted elements [duplicate]
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我想从数组中选择随机项,但要具有一定的概率分布。
目前我正在:
    myarray =[5,5,5,95]
这让我有75%的机会获得5分,而25%的机会获得95分。

但是我还有很多数字,要写出所有这些数字要花费太多时间,有没有更快/更好的方法呢?

最佳答案

您可以使用对象包含任何valueweight属性的数字组成的数组。



// data
const samples = [
  { value: 5, weight: 75 },
  { value: 95, weight: 25 }
];

// requested method
function randomSample (samples) {
  // [0..1) * sum of weight
  let sample =
    Math.random() *
    samples.reduce((sum, { weight }) => sum + weight, 0);

  // first sample n where sum of weight for [0..n] > sample
  const { value } = samples.find(
    ({ weight }) => (sample -= weight) < 0
  );

  return value;
}

// demo
const counts = { 5: 0, 95: 0 };

Array
  // take a million random samples
  .from({ length: 1000000 }, () => randomSample(samples))
  // count each sample
  .forEach(value => { counts[value]++; });

console.log(counts);





数据不必按任何特定顺序排列,权重也不必累加为任何特定总和。

09-16 10:42