EN
JavaScript - random values from array with probability (different probability per item)
9
points
In this short article, we would like to show how in JavaScript, get random items from an array using different randomization probabilities per item.
The main idea used in the below example to randomize items with different probabilities is to create an array that represents items distribution - items are repeated many times to affect randomization.
Quick solution:
// ONLINE-RUNNER:browser;
const createDistribution = (weights, size) => {
const distribution = [];
const sum = weights.reduce((a, b) => a + b);
const quant = size / sum;
for (let i = 0; i < weights.length; ++i) {
const limit = quant * weights[i];
for (let j = 0; j < limit; ++j) {
distribution.push(i);
}
}
return distribution;
};
const randomIndex = (distribution) => {
const index = Math.floor(distribution.length * Math.random()); // random index
return distribution[index];
};
const randomItem = (array, distribution) => {
const index = randomIndex(distribution);
return array[index];
};
// Usage example:
const array = ['John', 'Chris', 'Ann']; // used values in radomization
const weights = [ 0.5 , 0.2 , 0.3 ]; // specific items probability (0.5 + 0.2 + 0.3 = 1.0)
// 50% + 20% + 30% = 100%
const distribution = createDistribution(weights, 10); // 10 - describes distribution array size (it affects on precision - you can use bigger value to get more precise results)
for (let i = 0; i < 10; ++i) {
console.log(randomItem(array, distribution));
}
Example output:
John
Chris
Ann
Chris
Chris
Ann
John
John
Ann
John
Note: the above logic returns items keeping approximate probability (as it happens with probability).
Hint: for the greater amount of randomItem() function calls you will see the the numbers of array items goes to the defined probabilities.