【问题标题】:Change chances of picking a random string改变选择随机字符串的机会
【发布时间】:2020-06-07 00:28:03
【问题描述】:

我希望 Anna 有 67% 的几率被随机选中,Bob 有 30% 的变化,Tom 有 3% 的几率。有没有更简单的方法来做到这一点?

这是我目前所拥有的:

var nomes = ['Anna', 'Bob', 'Tom'];
var name = nomes[Math.ceil(Math.random() * (nomes.length - 1))];
console.log(name);

【问题讨论】:

  • 您能用您使用的编程语言标记您的帖子吗?我假设JavaScript。
  • 添加语言并更正!对不起!

标签: javascript arrays random


【解决方案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));

【讨论】:

    【解决方案2】:

    这里有一个简短的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多