问题描述
我需要随机生成与7个插槽Java中的数组。所有这些槽必须具有至少1的数值,但结合,具有的另一个限定数的合计值。他们也都需要有一个int值,没有1.5或0.9816465684646号码。例如:
I need to randomly generate an array with 7 slots in Java. All these slots must have a value of at LEAST 1, but combined, have a total value of another defined number. They also all need to be an int value, no 1.5 or 0.9816465684646 numbers.Example:
int a=10;
int[] ar = new int[7]
ar[0] = 1
ar[1] = 1
ar[2] = 2
ar[3] = 2
ar[4] = 1
ar[5] = 2
ar[6] = 1
我希望它产生类似的东西,但如果INT A = 15,所有数字将共有15个以任何顺序
I want it to generate something like that, but if int a=15, all the numbers would total 15 in any order
推荐答案
标准的方式来产生N个随机数的增加给定的准则是,想你之和为数字线,生成N-1个随机点行,排序他们,然后使用你的最终值点之间的差异。为了获得最小的1,从您的总和减去n启动,运行给出的算法,再加入1回各段。
The standard way to generate N random numbers that add to a given sum is to think of your sum as a number line, generate N-1 random points on the line, sort them, then use the differences between the points as your final values. To get the minimum 1, start by subtracting N from your sum, run the algorithm given, then add 1 back to each segment.
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");
}
}
这篇关于如何生成随机数,加起来就是一个明确的总数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!