Choosing something 35% more often

54 Views Asked by At

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.

2

There are 2 best solutions below

0
On

Let p be the probability in which a "normal" element is chosen. Then a "special" element should be chosen with probability 1.35*p. Correct?

Then you can calculate p by knowing the number of normal and special elements (sum of all probabilities should be 1). To actually choose the element, you should use a random (uniformly distributed) floating point value and do the calculations for the pick yourself.

If you are ok with 33.3...% higher probability you could alternatively throw 3 copies of the normal and 4 copies of the special elements into the array for randChoice().

0
On

Generally speaking:

One has an array of $n$ elements, of which the first $k$, say, are special: They are the ones that are to be selected $r$ times as often as the others. (For your specific numbers, $r = 1.35$.)

Let $rp$ be the probability assigned to those special elements, and $p$ be the one assigned to the rest. Then we have

$$ krp+(n-k)p = 1 $$ $$ [n-k(1-r)]p = 1 $$ $$ p = \frac{1}{n-k(1-r)} $$

or, if we write $r = 1+s$, where $s$ is the extra "lift" in the probability, then

$$ p = \frac{1}{n+sk} $$

For your specific case, then, we have

$$ p = \frac{1}{n+0.35k} $$

That is the probability of the non-special elements; the special elements are selected with probability

$$ rp = \frac{1.35}{n+0.35k} $$