Search code examples
javaalgorithminteger-partition

Integer Partition in Java


Here is my code to do this. It works for the string representation, but not the ArrayList<ArrayList<Integer>> one.

public static void partition(int n) {
    partition(n, n, "",
            new ArrayList<ArrayList<Integer>>(),
            new ArrayList<Integer>());
}

public static void partition(int n, int max, String temp,
                             ArrayList<ArrayList<Integer>> master,
                             ArrayList<Integer> holder) {
    if (n == 0) {
        ArrayList<Integer> temp1 = new ArrayList<Integer>();
        for (int i = 0; i <= holder.size(); i++) {
            temp1.add(holder.get(0));
            holder.remove(0);
        }
        master.add(temp1);
        System.out.println(temp);
    }

    for (int i = Math.min(max, n); i >= 1; i--) {
        holder.add(i);
        partition(n - i, i, temp + " " + i, master, holder);
    }
}

The reason that I am doing the funny business with temp1 is that if I were to just add temp to master, the previous elements would change (all elements in master would be references pointing to the same place) so this is my attempt at a deep copy + clear.

The string works. Why doesn't the ArrayList<ArrayList<Integer>>? And how can I fix it?

Output of the ArrayList<ArrayList<Integer>> is:

[[5], [4, 1], [3, 2], [1, 1], [2, 2], [1, 1, 1], [1, 1, 1, 1]]

Solution

  • You are mixing up your holder array inside the if branch which you shouldn't do. Try the following:

    public static void partition(int n, int max, String temp,
                                 ArrayList<ArrayList<Integer>> master,
                                 ArrayList<Integer> holder) {
        if (n == 0) {
            ArrayList<Integer> temp1 = new ArrayList<Integer>();
            for (int i = 0; i < holder.size(); i++) {
                temp1.add(holder.get(i));
            }
            master.add(temp1);
            System.out.println(temp);
        }
    
        for (int i = Math.min(max, n); i >= 1; i--) {
            holder.add(i);
            partition(n - i, i, temp + " " + i, master, holder);
            holder.remove(holder.size() - 1);
        }
    }