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

后端 未结 8 838
忘掉有多难
忘掉有多难 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:37

    Here's one way to do it, that avoids (most) magic numbers and provides a decent distribution of numbers though all will be smaller than other possible solutions.

    public static void n_random(int count, int finalSum)
    {
        Random r = new Random();
        int numbers[] = new int[count];
        int sum = 0;
        for (int i = 0; i < count - 1; i++)
        {
            numbers[i] = r.nextInt((finalSum - sum) / 2) + 1;
            sum += numbers[i];
        }
        numbers[count - 1] = finalSum - sum;
    
        StringBuilder numbersString = new StringBuilder("Random number list: ");
        for (int i = 0; i < count; i++)
            numbersString.append(numbers[i] + " ");
        System.out.println(numbersString);
    }
    
    public static void main(String[] args)
    {
        n_random(9, 250);
    }
    

提交回复
热议问题