Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

division an integer into k parts

I'm programming in java and I need to formulate an algorithm. The requirements of the algorithm are:

  • We have 3 Integer variables n, m, k;
  • We want to divide 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.
  • We want all possible combinations with the allowed integers.

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.

like image 764
ali khorshidi rozbahani Avatar asked Jun 24 '15 09:06

ali khorshidi rozbahani


1 Answers

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);
    }
}
like image 142
David Pérez Cabrera Avatar answered Sep 21 '22 16:09

David Pérez Cabrera