生成添加到给定总和的 N 个随机数的标准方法是将总和视为数轴,在该线上生成 N-1 个随机点,对它们进行排序,然后使用点之间的差异作为最终值。要获得最小值 1,首先从总和中减去 N,运行给定的算法,然后将 1 加回每个段。
public class Rand {
public static void main(String[] args) {
int count = 8;
int sum = 100;
java.util.Random g = new java.util.Random();
int vals[] = new int[count];
sum -= count;
for (int i = 0; i < count-1; ++i) {
vals[i] = g.nextInt(sum);
}
vals[count-1] = sum;
java.util.Arrays.sort(vals);
for (int i = count-1; i > 0; --i) {
vals[i] -= vals[i-1];
}
for (int i = 0; i < count; ++i) { ++vals[i]; }
for (int i = 0; i < count; ++i) {
System.out.printf("%4d", vals[i]);
}
System.out.printf("\n");
}
}