Java的:划分成若干部分等于或接近对方 [英] Java: divide number into equals parts or approximate to each other
问题描述
我有一个NUMER = 20。我要划分这个数字到N等于部分或接近对方。 Ñ也许从1至20个
I have a numer = 20. And I want to divide this number into N equals parts or approximate to each other. N maybe from 1 to 20.
在我写这篇code:
ArrayList<Integer> c = new ArrayList<>();
int num = 20;
int count = N; //where N some number (from 1 to 20)
int val = (int) Math.floor(num / count);
for (int i = 0; i < count; i++) {
c.add(val);
}
c.set(0, c.get(0) + num - sum(c));
它工作正常,例如,当计数= N = 3。我得到08分,6,6(8 + 6 + 6 = 20)。但是,如果算上= N = 12我得到一个结果:9,1,1,1,1,1,1,1,1,1,1,1(总和= 20)。我想这个结果将在明年1,2,2,2,2,2,2,2,2,1,1,1(总和= 20)。这可能吗?
It works fine, for example, when count = N = 3. I get: 8, 6, 6 (8+6+6=20). But if count = N = 12 I get next result: 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 (sum = 20). I want that result will be next: 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1 (sum = 20). Is that possible?
推荐答案
您计算的大小的下一步的一部分,那么减少的值,并重复:
You calculate the size of the next part, then reduce the values and repeat:
private static int[] splitIntoParts(int whole, int parts) {
int[] arr = new int[parts];
int remain = whole;
int partsLeft = parts;
for (int i = 0; partsLeft > 0; i++) {
int size = (remain + partsLeft - 1) / partsLeft; // rounded up, aka ceiling
arr[i] = size;
remain -= size;
partsLeft--;
}
return arr;
}
如果你想,该方法可被挤压,但正如上面留下它是更好,因为它把这些参数作为不可改变的,明确的逻辑:
If you want, the method can be squeezed, though leaving it as above is better because it treats the parameters as immutable and clarifies the logic:
private static int[] splitIntoParts(int whole, int parts) {
int[] arr = new int[parts];
for (int i = 0; i < arr.length; i++)
whole -= arr[i] = (whole + parts - i - 1) / (parts - i);
return arr;
}
测试的
for (int parts = 0; parts <= 25; parts++)
System.out.println(parts + ": " + Arrays.toString(splitIntoParts(20, parts)));
输出的
0: []
1: [20]
2: [10, 10]
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, 0, 0, 0]
注意 0
返回空数组。添加如果
语句,如果它失败了。负值将与 NegativeArraySizeException
失败。正如你所看到的,有太多的部分将 0的简单收益部分
尺寸。再次,增加如果
语句如果失败了
Notice that 0
returns empty array. Add if
statement if it should fail. Negative values will fail with NegativeArraySizeException
. As you can see, too many parts will simple return parts of 0
size. Again, add if
statement if that should fail
这篇关于Java的:划分成若干部分等于或接近对方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!