更改随机字符串的机会

问题描述 投票:4回答:2

我希望安娜有67%的机会被随机挑选,鲍勃有30%的改变,汤姆有3%的机会。有没有更简单的方法可以做到这一点?

这是我到目前为止所拥有的:

var nomes = ['Anna', 'Bob', 'Tom'];
var name = nomes[Math.ceil(Math.random() * (nomes.length - 1))];
console.log(name);
javascript arrays random
2个回答
1
投票

基于此Stack Overflow,我认为以下代码将为您工作:

function randomChoice(p) {
  let rnd = p.reduce((a, b) => a + b) * Math.random();
  return p.findIndex(a => (rnd -= a) < 0);
}

function randomChoices(p, count) {
  return Array.from(Array(count), randomChoice.bind(null, p));
}

const nomes = ['Anna', 'Bob', 'Tom'];

const selectedIndex = randomChoices([0.67, 0.3, 0.03], nomes);
console.log(nomes[selectedIndex]);

// Some testing to ensure that everything works as expected:

const odds = [0, 0, 0];

for (let i = 0; i < 100000; i++) {

  const r = randomChoices([0.67, 0.3, 0.03], nomes);
  odds[r] = odds[r] + 1;

}

console.log(odds.map(o => o / 1000));

0
投票

这是您的简短解决方案:

function pick(){
  var rand = Math.random();
  if(rand < .67) return "Anna";
  if(rand < .97) return "Bob";
  return "Tom";
}

console.log( pick() );
© www.soinside.com 2019 - 2024. All rights reserved.