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}