将数字分成更小的随机整数 [英] Dividing a number into smaller random ints
问题描述
所以我需要的东西基本上在主题中描述.
So what i need is basically described in the subject.
就像我要输入数字 12 和它应该分成的部分数量一样,我希望它返回类似(包含 4 个部分)8、2、1、1 的内容.但不能加倍,因为我需要这些值内部
我之前找到了一个答案,但它只适用于双打.不是整数.
(这是我找到的)
Like if i would put in number 12 and amount of parts it should devide into, i would like it to return something like (with 4 parts) 8, 2, 1, 1. But not doubles because i need the values as int.
I had found one answer earlier but it only worked using doubles. not ints.
(this is the one i found)
public double[] divideUniformlyRandomly(double number, int part) {
double uniformRandoms[] = new double[part];
Random random = new Random();
double mean = number / part;
double sum = 0.0;
for (int i=0; i<part / 2; i++) {
uniformRandoms[i] = random.nextDouble() * mean;
uniformRandoms[part - i - 1] = mean + random.nextDouble() * mean;
sum += uniformRandoms[i] + uniformRandoms[part - i -1];
}
uniformRandoms[(int)Math.ceil(part/2)] = uniformRandoms[(int)Math.ceil(part/2)] + number - sum;
return uniformRandoms;
我曾尝试通过这样做来更改此代码以使用 Int:
I had tried changing this code to work using Ints by doing this:
public int[] divide(int number) {
int part = getDivider(number);
int uniformRandoms[] = new int[part];
Random random = new Random();
int mean = number / part;
int sum = 0;
for (int i=0; i<part / 2; i++) {
uniformRandoms[i] = random.nextInt() * mean;
uniformRandoms[part - i - 1] = mean + random.nextInt() * mean;
sum += uniformRandoms[i] + uniformRandoms[part - i -1];
}
uniformRandoms[(int)Math.round(part/2)] = uniformRandoms[(int)Math.round(part/2)] + number - sum;
for(int i : uniformRandoms)
System.out.println(i);
return uniformRandoms;
}
但是当使用 number: 512 并使用 10 个部分(getDivider() 将返回 10)运行它时,它会输出:
But when running that using number: 512 and using 10 parts (getDivider() will return 10) itll output this:
-1058809647, -2102647561, 469849949, 1627965716, -290084223, -33347991
还有更多此类数字.
谢谢.
推荐答案
假设每一项至少应为 1.
Assuming every term should at least be 1.
public int[] divide(int number, int parts) {
int[] randoms = new int[parts];
Arrays.fill(randoms, 1); // At least one
int remainder = number - parts;
Random random = new Random();
for (int i = 0; i < parts - 1 && remainder > 0; ++i) {
int diff = random.nextInt(remainder);
randoms[i] += diff;
remainder -= diff;
}
randoms[parts - 1] += remainder;
Arrays.sort(randowms);
// Reverse (for getting a descending array):
for (int i = 0, j = parts - 1; i < j; ++i, --j) {h
int temp = randoms[i];
randoms[i] = randoms[j];
randoms[j] = temp;
}
return randoms;
}
这不是均匀分布的.因为那个可以迭代直到余数变为 0,每次随机选择一个索引来增加.或者.玩得开心.
This is not uniformly distributed. For that one could iterate till remainder becomes 0, everytime randomly picking an index to increase. Or so. Have fun.
这是家庭作业吗?
这篇关于将数字分成更小的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!