Languages
[Edit]
EN

JavaScript - random values from array with probability (different probability per item)

9 points
Created by:
JustMike
30450

In this short article, we would like to show how in JavaScript, get random items from an array using different randomization probabilities per item.

Example randomization probabilities.
Example randomization probabilities.

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 on randomization.

Quick solution:

// ONLINE-RUNNER:browser;

const createDistribution = (array, weights, size) => {
    const distribution = [];
    const sum = weights.reduce((a, b) => a + b);
  	for (let i = 0; i < array.length; ++i) {
      	const count = (weights[i] / sum) * size;
      	for (let j = 0; j < count; ++j) {
          	distribution.push(i);
        }
    }
  	return distribution;
};

const randomIndex = distribution => {
  	const index = Math.floor(distribution.length * Math.random());  // random index
    return distribution[index];  
};


// Usage example:

const array =   ['John', 'Chris', 'Ann'];  // used values in radomization
const weights = [  0.5 ,    0.2 ,  0.3 ];  // specific items probability (5 + 2 + 3 = 10)

const distribution = createDistribution(array, weights, 10);  // 10 - describes distribution array size (it affects on precision)

for (let i = 0; i < 10; ++i) {
    const index = randomIndex(distribution);
    console.log(array[index]);  // random value located in the array
}

Example output:

John
Chris
Ann
Chris
Chris
Ann
John
John
Ann
John
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join