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 void n_random()
{
Random r = new Random();
ArrayList<Integer> load = new ArrayList<Integer>();
int temp = 0;
int sum = 0;
for (int i = 1; i <= 9; i++) {
if (!(i == 9)) {
temp = r.nextInt(250 - sum);
System.out.println("Temp " + (i) + " " + temp);
load.add(temp);
sum += temp;
} else {
int last = (250 - sum);
load.add(last);
sum += last;
}
}
System.out.println("Random arraylist " + load);
System.out.println("Sum is "+ sum);
}
Where is my mistake or where i should improve my code or any other solution?
I would suggest using:
That will make sure that:
However the distribution of the results is probably biased.
Example output:
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 0An alternative which probably gives a better distribution is to take random numbers and scale them to get to the desired sum. Example implementation:
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.
A call to
Random.nextInt(n)
will return an integer between 0 and n-1try
temp = r.nextInt(250 - sum) + 1;
and see if that solves your issue.this is javascript alternative
Your code line:
... will generate a pseudo-random from
0
(included) to250 - sum
(excluded).See API for
Random.nextInt
.I won't try to solve all your problem here, but simply adding
1
to the expression above would guarantee that it never returns0
.All remaining adaptations up to you though :)
For instance if
250 - sum - 1
evaluates to negative, then you'll throw anIllegalArgumentException
.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.