You are not logged in.
Pages: 1
The following Java code will generate all distinct sublists of a specified size from a list. This is equivalent to the generation of all subsets of a specified cardinality from the supplied set (List abstraction is used instead of Set for convenience of the API to this recursive method) . By calling this method for size 0 to N where N is the cardinality of the set, you will get all elements of the powerset.
/** Returns all combinations of items of the specified size from the source
* list. Order is preserved, such as if a is always before b in the source,
* there will not be a combination where a is after b. Unlike permutations,
* order is not significant such that [a,b] is equivalent to the combination
* [b,a] and therefore latter will not be returned unless a or b appears
* more than once in the source list. */
public static <T> List<List<T>> getCombinations(List<T> source, int size) {
if (size < 0 || size > source.size())
throw new IllegalArgumentException("Combination size must be greater " +
"than or equal to 0 and less than or equal to the size of the " +
"source list (" + source.size() + "). Current size of " + size +
" is invalid.");
List<List<T>> combinations = new ArrayList<List<T>>();
if (size == 0)
combinations.add(new ArrayList<T>());
else if (size == source.size())
combinations.add(new ArrayList<T>(source));
else
for (int i = 0; i < source.size() - size + 1; i++) {
T head = source.get(i);
List<T> subList = source.subList(i + 1, source.size());
for (List<T> subCombination: getCombinations(subList, size - 1)) {
subCombination.add(0, head);
combinations.add(subCombination);
}
}
return combinations;
}
V.
Pages: 1