Search code examples
javaarraysrandomprobability-densitynon-uniform-distribution

Generate an array of random integers with non-uniform distribution


I want to write Java code to produce an array of random integers in the range [1,4]. The array's length is N, which is provided at run time. The problem is that the range [1,4] is not uniformly distributed:

enter image description here

It means that if I create arrays with N=100, the number '1' will appear averagely 40 times in an array, number '2' 10 times, and so on.

For now I am using this code to generate uniform-distributed random numbers in range [1,4]:

public static void main(String[] args)
    {
        int N;
        System.out.println();
        System.out.print("Enter an integer number: ");
        N = input.nextInt();
        int[] a = new int[N];
        Random generator = new Random();
        for(int i = 0; i < a.length; i++)
        {
            a[i] = generator.nextInt(4)+1;
        }
    }

How do I implement it with a the non-uniform distribution as shown in the graph above?


Solution

  • Here's a way to do it, starting from your code:

    public static void main(String[] args){
        int N;
        System.out.println();
        System.out.print("Enter an integer number: ");
        N = input.nextInt();
        int[] a = new int[N];
        Random generator = new Random();
        for (int i = 0; i < a.length; i++) {
            float n = generator.nextFloat();
            if (n <= 0.4) {
                a[i] = 1;
            } else if (n <= 0.7) {
                a[i] = 3;
            } else if (n <= 0.9) {
                a[i] = 4;
            } else {
                a[i] = 2;
            }
        }
    }
    

    UPDATE: at @pjs' suggestion, select numbers in order of desdencing probability so you tend to exit the if block earlier