I'm trying to split a list into several parts. I need to find all possible ways n integers can be distributed over k groups. For example, if my list is {1,2,3,4,5,6,7}, I need to find all ways this can be split into k=3 groups. I want to emphasise that I need to know all possible ways things can be split, which becomes a massive amount for large values of n and/or k. However, I expect these to stay relatively small (single digits), so there should be no problem. I have this piece of code that splits the list in two:
List<List<Integer>> results;
public void findAllSublists(List<Integer> list, int minimalLengthOfSublist) {
results = new ArrayList<List<Integer>>();
List<List<Integer>> sublists = new ArrayList<List<Integer>>();
for (int i = 0; i <= list.size(); i++) {
recursiveSublist(list, sublists, i, new ArrayList<Integer>(), 0);
}
for (List<Integer> subList : sublists) {
if (subList.size() >= minimalLengthOfSublist) {
results.add(subList);
}
}
}
private static void recursiveSublist(List<Integer> list, List<List<Integer>> subLists, int sublistSize, List<Integer> currentSubList, int startIndex) {
if (sublistSize == 0) {
subLists.add(currentSubList);
} else {
sublistSize--;
for (int i = startIndex; i < list.size(); i++) {
List<Integer> newSubList = new ArrayList<Integer>(currentSubList);
newSubList.add(list.get(i));
recursiveSublist(list, subLists, sublistSize, newSubList, i + 1);
}
}
}
I realise you might do another level of recursion, splitting sublists into smaller sublists until the desired amount of sublists is achieved. But I am failing to see the most efficient way of doing this, recursion not being my strong suit and all, so I was hoping someone could point me in the right direction. Help would be much appreciated. Thank you.
`, so the full set of combinations must be a `List
– Andreas Dec 05 '15 at 16:21>`, and your code doesn't have such a list, so it cannot provide the requested result.