jeudi 13 août 2015

Selecting an element from an array 35% more often

If I want to select an element from an array at random, the following will choose each element roughly at 1/L percent of the time:

/**
 * @param {Array} choices
 */
function randChoice(choices){
   var index = Math.random() * choices.length | 0;
   return choices[index];
}

If the array has 2 elements, each element will be chosen about 50% of the time.

If the array has 23 elements, each element will be chosen about 4.35% of the time.

What I'm trying to accomplish is to randomly select from all elements in the array, but some of them I select 35% more often than the others.

Simplified example:

I have two arrays, one with elements to be chosen 1/N percent of the time, and the other has values to be chosen 35% more often.




Aucun commentaire:

Enregistrer un commentaire