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));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…