I'm working on a problem where I want to group a list by two's and get all possible combinations.
for example: for the list [A,B,C,D];
I'm trying to create a method that will give me the ff:
A and BCD
B and ACD
C and ABD
D and ABC
AB and CD
AC and BD
AD and BC
etc...
I know that recursion is the answer but I don't know where to start. Can someone point me to the right direction?
My attempt so far:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
for (int x = 1; x < list.size() - 1; x++) { //how many elements in one group
for (int i = 0; i < list.size(); i++) { //get first group..
List<Integer> chosenIndices = new ArrayList<>(); //?..
chosenIndices.add(i); // good for one element grouping only..
List<String> firstGroup = getFirstGroup(list, chosenIndices); //method to pick chosenindices
List<String> secondGroup = getRestofList(list, chosenIndices); //method to exclude chosenIndices
System.out.println(firstGroup + ": " + secondGroup);
}
}
this takes care of the combination where the first group contains one element but I can't figure out how to get the next iteration and come up with a list of two elements for the first group. I hope this makes sense.
My first answer maybe was useful, but it worked bad. Sorry.
Here is another example. It is based on the rules of combinatorics:
where n - is the number of elements total, and k is the number of elements is group
The output will be: