Home > front end >  Generating a discrete random variable in Java?
Generating a discrete random variable in Java?

Time:12-01

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.

CodePudding user response:

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];
}

CodePudding user response:

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];
}

CodePudding user response:

This is what I came up with

import java.util.Random;

public class RandomNumber {
    public static void main(String[] args) {
        double[] probabilities = {.2, .1, .3, .4};
        double[] outcomes = {4, 5, 8, 11.5};

        double discreteRV = RandomNumber.randPMF(probabilities, outcomes);
    }
    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];
    }
}
  • Related