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.
>Solution :
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];
}