vendredi 20 mars 2020

How to generate random numbers from a array whose sum is N (Not Defined) in ANDROID Java?

I have a specific range in an array.

 private int[] arr = {0, 1, 2, 3, 4, 6};

I've successfully generated the numbers up to the sum, but the random numbers are not in my array range.

 private ArrayList<Integer> random(int targetSum, int numberOfDraws) {
        Random r = new Random();
        ArrayList<Integer> load = new ArrayList<>();

        //random numbers
        int sum = 0;
        for (int i = 0; i < numberOfDraws; i++) {
            int next = r.nextInt(targetSum) + 1;
            load.add(next);
            sum += next;
        }

        //scale to the desired target sum
        double scale = 1d * targetSum / sum;
        sum = 0;
        for (int i = 0; i < numberOfDraws; i++) {
            load.set(i, (int) (load.get(i) * scale));
            sum += load.get(i);
        }

        //take rounding issues into account
        while (sum++ < targetSum) {
            int i = r.nextInt(numberOfDraws);
            load.set(i, load.get(i) + 1);
        }

        return load;
    }

Where I'm making a mistake? What new solution should I improve?

Thanks.




Aucun commentaire:

Enregistrer un commentaire