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
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);
}