1

I need a recursive solution which returns any combination of n subset from k set (in mathematical sense). I have an ArrayList and I want return any possible n-size subsets from recursive method. Order doesn't matter. So if I have set of employees {Jim, Tom, Ann, John} and want 2 of them I should get:

{Jim Tom}{Jim Ann}{Jim John}{Tom Ann}{Tom John}{Ann John}

I found this https://stackoverflow.com/a/16256122/10929764 but it only prints out result. I modified it a bit to add any combination to ArrayList and return it, but it doesn't work properly. Here is a code:

    public ArrayList<Employee[]> combinationsOfEmployee(ArrayList<Employee>sourceList, int selected, int startIndex, Employee[] result, ArrayList<Employee[]>allResults){
        if(selected == 0){
            for(int i=0; i<result.length; i++){
                System.out.print(result[i].getLastName() + "  ");
            }
            System.out.println("");
            allResults.add(result);
            return allResults;
        }
        for(int i=startIndex; i<=sourceList.size() - selected; i++){
            result[result.length - selected] = sourceList.get(i);
            combinationsOfEmployee(sourceList, selected - 1, i + 1, result, allResults);
        }
        return allResults;
    }

It prints out properly all combinations, but adds the same values all the time to ArrayList. So allResults is

{Ann, John}{Ann, John}{Ann, John}{Ann, John}{Ann, John}{Ann, John}

instead of:

{Jim Tom}{Jim Ann}{Jim John}{Tom Ann}{Tom John}{Ann John}

  • *"Is it possible to return ArrayList from recursive method?"* - yes, certainly. But that is not really the question, please refine the title to reflect your *actual* question. – luk2302 Jan 18 '19 at 08:49
  • Have you debugged your code to inspect what the values in the list actually are after each statement / recursive call? For completion sake it would be VERY helpful to show the most basic possible version of `Employee` and how you call the method `combinationsOfEmployee` in the first place. – luk2302 Jan 18 '19 at 08:51

1 Answers1

1

You are wondering why it prints it fine while the returned list seems to have the exact same array at each position.
That's because it's the exact same array (same reference to the same object). Since in your solution you are using only one array, when you call allResults.add(result), you add the reference to your only array in the list. Then you keep modifying it when you look for the other combinations. That's why your list only contains the last combination found.

The solution to this is to add a new array each time you find a combination by adding a copy of your current array to your list. Simply replace

allResults.add(result);

by

allResults.add(Arrays.copyOf(result, result.length));

That way, every element of your list points to a different array.

Ricola
  • 2,621
  • 12
  • 22