I\'m trying to generate a collection of all 2^N - 1 possible combinations of a given List of length N. The collection will map the number of elements in a combination to an
I test the code proposed by Elist and I found errors.
Here is a proposed correction : (in the last else of the function getPermutation(), I made two changes)
public class OrderedPowerSet {
private ArrayList inputList;
public int N;
private Map>> map =
new HashMap>>();
public OrderedPowerSet(ArrayList list) {
inputList = list;
N = list.size();
}
public List> getPermutationsList(int elementCount) {
if (elementCount < 1 || elementCount > N) {
throw new IndexOutOfBoundsException(
"Can only generate permutations for a count between 1 to " + N);
}
if (map.containsKey(elementCount)) {
return map.get(elementCount);
}
ArrayList> list = new ArrayList>();
if (elementCount == N) {
list.add(new HashSet(inputList));
} else if (elementCount == 1) {
for (int i = 0 ; i < N ; i++) {
Set set = new HashSet();
set.add(inputList.get(i));
list.add(set);
}
} else {
for (int i = 0 ; i < N-elementCount ; i++) {
@SuppressWarnings("unchecked")
ArrayList subList = (ArrayList)inputList.clone(); // one change
subList.remove(0);
OrderedPowerSet subPowerSet =
new OrderedPowerSet(subList);
for (Set s : subPowerSet.getPermutationsList(elementCount-1)) {
Set set = new HashSet();
set.add(inputList.get(i));
set.addAll(s);
list.add(set); // second change
}
}
}
map.put(elementCount, list);
return map.get(elementCount);
}
}