I am trying to get all possible combinations of size K from a list of size N.
I have a List that takes "Human" objects and I am trying to create a new ArrayList which will be filled with List objects. Each of the Lists will be a different combination of "Human" objects.
A simple example with numbers would be: From a list consisting 1,2,3 I want to get an ArrayList which looks like this: [[1,2], [1,3], [2,3]]
I also wouldn't mind if it looks like this: [[1], [2], [3], [1,2], [1,3], [2,3]]
Here is my code:
public void combination(List<Human> people, int k, ArrayList<List> result) {
if (people.size() < k) {
return;
}
if (k == 1) {
for (Human hum : people) {
List<Human> combinations = new ArrayList<Human>();
combinations.add(hum);
result.add(combinations);
}
}
else if (people.size() == k) {
List<Human> combinations = new ArrayList<Human>();
for (Human hum : people) {
combinations.add(hum);
}
result.add(combinations);
}
else if (people.size() > k) {
for (int i = 0; i < people.size(); i++) {
List<Human> combinations = new ArrayList<Human>();
combinations.add(people.get(i));
result.add(combinations);
combination(people.subList(i + 1, people.size()), k - 1, result);
}
}
}
I am using the last method in this site as a reference: https://hmkcode.com/calculate-find-all-possible-combinations-of-an-array-using-java/
At the moment I get the correct number of results in my new ArrayList but each List inside only consist of a single Human.
I highly suspect the problem lies in the last else if because I have hard time understanding the recursion.
Please feel free to ask any questions or suggest any other implementation for this.