Generate n random numbers whose sum is m and all numbers should be greater than zero

后端 未结 8 832
忘掉有多难
忘掉有多难 2020-12-18 04:04

I want to generate 9 non zero random numbers whose sum is 250. I have tried following code it gives me 9 random numbers but some numbers are zero.

 public vo         


        
相关标签:
8条回答
  • 2020-12-18 04:56

    I would suggest using:

    temp = r.nextInt((250 - sum) / (9 - i)) + 1;
    

    That will make sure that:

    • each number is strictly positive
    • you won't use the full "250 allowance" before reaching the 9th number

    However the distribution of the results is probably biased.

    Example output:

    Random arraylist [18, 28, 22, 19, 3, 53, 37, 49, 21]

    Explanation:

    • (250 - sum) is the amount left to reach 250, so you don't want to go over that
    • / (9 - i) if your sum has reached for example 200 (need 50 more) and you have 5 more to go, make sure the next random number is not more than 10, to leave some room for the next 4 draws
    • + 1 to prevent 0

    An alternative which probably gives a better distribution is to take random numbers and scale them to get to the desired sum. Example implementation:

    public static void n_random(int targetSum, int numberOfDraws) {
        Random r = new Random();
        List<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);
        }
    
        System.out.println("Random arraylist " + load);
        System.out.println("Sum is "+ (sum - 1));
    }
    
    0 讨论(0)
  • 2020-12-18 05:01

    I don't see where you've checked to make sure that zero is excluded. Add a check before you insert it into the array.

    Too many "magic numbers" in this code to suit me.

    0 讨论(0)
提交回复
热议问题