[英]Finding a combination of numbers of size N that sum up to a given number
Given the number C and a number N. I want to find N numbers that sum up to C and the difference between the highest and the lowest of these number should not be more than one. 给定数字C和数字N。我想找到总计为C的N个数字,这些数字的最高和最低之间的差应不超过一个。 For example:
例如:
Given these -> (C = 26, N = 7) -- I need an algorithm that would find these -> [4 4 4 4 4 3 3] 给定这些->(C = 26,N = 7)-我需要一种可以找到这些-> [4 4 4 4 4 3 3]的算法
C = 11, N = 5 - [3 2 2 2 2] C = 11,N = 5-[3 2 2 2 2]
C = 17, N = 4 - [5 4 4 4] C = 17,N = 4-[5 4 4 4]
C = 10, N = 3 - [4 3 3] C = 10,N = 3-[4 3 3]
C = 5, N = 2 - [3 2] C = 5,N = 2-[3 2]
Edit: Had a mistake in the examples. 编辑:在示例中有一个错误。
I did this: 我这样做:
//N and C are declared above.
int[] numbers = new int[N];
int lowBound = C / N;
int Modulo = C % N;
for(int i = 0; i < numbers.length; i++) {
numbers[i] = lowBound;
}
while(Modulo > 0) {
for(int i = 0; i < numbers.length; i++) {
if(Modulo < 1) break;
numbers[i]++;
Modulo--;
}
}
Also i am sorry. 我也很抱歉。
I was just looking for a headstart, I am quite new here. 我只是想找个起点,我在这里很新。
From the comment section to the answer box 从评论部分到答案框
Turns out you don't need a loop for this, just math. 事实证明,您不需要循环,只需数学即可。
public class SolveCombination {
public static List<Integer> solve(int c, int n) {
int k = c / n;
int rk = k + 1;
int p = (c - (k * n));
return Stream.concat(Stream.generate(() -> rk).limit(p),
Stream.generate(() -> k).limit(n - p))
.collect(Collectors.toList());
}
}
jshell> solve(26, 7)
$7 ==> [4, 4, 4, 4, 4, 3, 3]
jshell> solve(17, 4)
$8 ==> [5, 4, 4, 4]
jshell> solve(10, 3)
$9 ==> [4, 3, 3]
jshell> solve(5, 2)
$10 ==> [3, 2]
jshell> solve(11, 5)
$11 ==> [3, 2, 2, 2, 2]
jshell> solve(0, 5)
$12 ==> [0, 0, 0, 0, 0]
jshell> solve(1, 5)
$13 ==> [1, 0, 0, 0, 0]
jshell> solve(0, 0)
| java.lang.ArithmeticException thrown: / by zero
| at solve (#6:2)
| at (#14:1)
jshell>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.