1

Today in interview they asked me this question? How to generate a discrete random variable in Java? I couldn't do it but I wonder the solution. They gave me an array:

double[] probabilities={.2,.1,.3,.4};
double[] outcomes ={4,5,8,11.5};

And this should give the answer:

double discreteRV = problem.randPMF(probabilities,outcomes);

I couldn't understand how to solve this question.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
cvsrt
  • 357
  • 4
  • 19

3 Answers3

5

Since all the probabilities will always add up to 1, you can generate a random number between 0 and 1 then iterate through the probabilities and subtract them. When the number is less than or equal to 0, the index of the last subtracted probability is the index of the outcome:

import java.util.Random;
public static double randPMF(double[] prob, double[] out) {
    double rand = Math.random();
    int index = -1;
    while (rand >= 0) {
        index++;
        rand -= prob[index];
    }
    return out[index];
}
Erik McKelvey
  • 1,650
  • 1
  • 12
  • 23
5

Here's my idea for a solution:

private double randPMF(double[] probabilities, double[] outcomes) {
    double random = Math.random();
    double p = 0;
    for (int i = 0; i < probabilities.length; i++) {
        p += probabilities[i];
        if (random < p) {
            return outcomes[i];
        }
    }
    return outcomes[outcomes.length - 1];
}
xtratic
  • 4,600
  • 2
  • 14
  • 32
0

This is what I came up with

    private static double randPMF(double[] probabilities, double[] outcomes) {
        int n = 10;
        boolean nNotFound;
        for (double probability: probabilities){
            nNotFound = true;
            while(nNotFound)
            if (probability*n == (double)((int)(probability*n)))
                break;
            else
                n *= 10;
        }
        double[] numbers = new double[n];
        //j tracks the probability/occurence
        int j;
        //k tracks the new array
        int k = 0;
        //i tracks each element in our old arrays
        for (int i = 0; i<probabilities.length; i++) {
            j = 0;
            while (j < (probabilities[i]*n)) {
            numbers[k] = outcomes[i];
            k++;
            j++;
            }
        }
        int index = new Random().nextInt(n);
        System.out.println(numbers.length);
        return numbers[index];
    }
David Tejuosho
  • 177
  • 1
  • 14