Change chances of picking a random string

Viewed 58

I would like Anna to have 67% chance of being picked randomly, Bob to have a 30% change, and Tom to have a 3% chance. Is there a simpler way to do this?

This is what I have so far:

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

Based on this Stack Overflow I think the following code will work for you:

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));

Here's a short solution for you:

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

console.log( pick() );

Related