I'm programming in java and I need to formulate an algorithm. The requirements of the algorithm are:
n
, m
, k
;n
into k
parts so that the sum of the k
-parts
are equal to n
and each part is an integer between 1
and m
.For example with input set:
n = 7; m = 3; k = 4
we have two different combinations that we can formulate:
7 = 2 + 2 + 2 + 1
and
7 = 3 + 2 + 1 + 1
thank you all.
The idea is a backtraking algorithm approach (with recursion), You can decrease parameters and get partials solutions and then check if you have a right solution.
public class Problem {
private static void algorithm(int n, int k, int m) {
algorithmRecursive(Collections.EMPTY_LIST, n, k, m, 1);
}
private static void algorithmRecursive(List<Integer> partial, int n, int k, int m, int min) {
if ( (k > 0) ) {
// Optimization
if ((n <= k * m) && (n >= k*min)){
for (int i = min; i <= Math.min(m, n); i++) {
List<Integer> newPartial = new ArrayList<>(partial);
newPartial.add(i);
algorithmRecursive(newPartial, n - i, k - 1, m, i);
}
}
} else if (n == 0) {
// Right solution
System.out.println(partial);
}
}
public static void main(String[] args) {
algorithm(7,4,3);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With