javaarraysrandomprobability-distribution

How to pick an element from an array with a probability distribution?


I have a mathematical/programming question about a problem I am trying to solve. Given this simple array of integers:

int[] goals = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Do you know how could I implement a function to pick an element from the array given a distributed probability like the one from this example?:

The probability distribution is of my choice, hardcoded to keep things simple.

Thank you very much for your inputs!


Solution

  • You can create an array of 100 elements, then for each number i in the array goals, put i into the new array n times where n equals the probability of i times the array size (100). Then randomly pick an element from the new array.

    You can increase the array size (100) to get a more precise result. The most precise result will be when you pick the array size that makes every n a whole number.

    Example:

    https://jsfiddle.net/o5hmjxd2/28/

    const x = [0,1,2,3,4,5,6,7,8,9];
    const p = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
    const l = 100;
    
    let y = [];
    
    
    for (const i = 0; i < x.length; i++) {
      y = y.concat(new Array(l*p[i]).fill(x[i]));
    }
    
    function getRandomInt(max) {
      return Math.floor(Math.random() * max);
    }
    
    // result
    console.log(y);
    console.log(y[getRandomInt(y.length - 1)])