ArrayList of Arrays gets overwritten everytime

I'm trying to use ArrayList in a recursive function. I'm trying to find the combinations of the array arr of size r. Like if I have an array

["A","B","C","D"]

I want to print :

A B C
A B D
A C D
B C D

But when I print my ArrayList in the recursive function it gives:

Call1 : ABC
Call2 : ABD
        ABD

And so on. ie every time the previous contents of the ArrayList are overwritten with the new content and the new content is also added to the end. Also in the Function calling the recursive function my ArrayList is not returned it just contains a list of Es.

In the function calling the recursive function I have something like

private static void combine(String[] arr, int r) {
    String[] res = new String[r];
    ArrayList<String[]> result = new ArrayList<String[]>();
    doCombine(arr, res, 0, 0, r, result);
    System.out.println("\nIn main" + result.size());
    for (Object[] array : result) {
        for (Object o : array)
            System.out.print("item: " + o);
        System.out.println();
    }
}

// This recursive function finds combinations
private static void doCombine(String[] arr, String[] res, int currIndex,
  int level, int r, ArrayList<String[]> result) {

    if (level == r) {
        printArray(res);
        String[] inter = new String[r];
        inter = res;
        result.add(inter);
        // Tryinh to see wht the array list has every time
        for (Object[] array : result) {
            for (Object o : array) {
                System.out.print("item: " + o);
            }
            System.out.println();
        }
        inter = null;
        return;
    }
    for (int i = currIndex; i < arr.length; i++) {
        counter.add();
        res[level] = arr[i];
        doCombine(arr, res, i + 1, level + 1, r, result);
    }
}

Please tell me what I am doing wrong.

Answers


Modify the code

    String[] inter = new String[r];
    inter = res;
    result.add(inter);

to

        String[] inter = new String[r];
        int k=0;
        for(String s:res){
            inter[k] = s;
            k++;
        }
        result.add(inter);

And the code work as Expected.

Output:

1

A B C

2

A B C

A B D

3

A B C

A B D

A C D

4

A B C

A B D

A C D

B C D


Need Your Help

Could Not find windows command to convert dos file to unix

windows unix text-files file-conversion eol

The scenario where I am stuck is that I have a normal windows text file 'command.txt' which I am copying on remote(unix) server from my local machine(windows) using 'pscp' command from cmd.