lundi 27 avril 2015

Array of random integers with fixed average in java

I need to create an array of random integers which a sum of them is 1000000 and an average of these numbers is 3. The numbers in the array could be duplicated and the length of the array could be any number.

I am able to find the array of random integers which the sum of them is 1000000.

    ArrayList<Integer> array = new ArrayList<Integer>();

    int a = 1000000;
    Random rn = new Random();
    while (a >= 1)
    {
        int answer = rn.nextInt(a) + 1;
        array.add(answer);
        a -= answer;
    }

However, I don't know how to find the random numbers with average of 3.




Aucun commentaire:

Enregistrer un commentaire