Create a power-set of: {"A", "B", "C"}.
Pseudo-code:
val set = {"A", "B", "C"}
val sets = {}
for item in set:
for set in sets:
sets.add(set + item)
sets.add({item})
sets.add({})
Algorithm explanation:
1) Initialise sets to an empty set: {}.
2) Iterate over each item in {"A", "B", "C"}
3) Iterate over each set in your sets.
3.1) Create a new set which is a copy of set.
3.2) Append the item to the new set.
3.3) Append the new set to sets.
4) Add the item to your sets.
4) Iteration is complete. Add the empty set to your resultSets.
Walkthrough:
Let's look at the contents of sets after each iteration:
Iteration 1, item = "A":
sets = {{"A"}}
Iteration 2, item = "B":
sets = {{"A"}, {"A", "B"}, {"B"}}
Iteration 3, item = "C":
sets = {{"A"}, {"A", "B"}, {"B"}, {"A", "C"}, {"A", "B", "C"}, {"B", "C"}, {"C"}}
Iteration complete, add empty set:
sets = {{"A"}, {"A", "B"}, {"B"}, {"A", "C"}, {"A", "B", "C"}, {"B", "C"}, {"C"}, {}}
The size of the sets is 2^|set| = 2^3 = 8 which is correct.
Example implementation in Java:
public static <T> List<List<T>> powerSet(List<T> input) {
List<List<T>> sets = new ArrayList<>();
for (T element : input) {
for (ListIterator<List<T>> setsIterator = sets.listIterator(); setsIterator.hasNext(); ) {
List<T> newSet = new ArrayList<>(setsIterator.next());
newSet.add(element);
setsIterator.add(newSet);
}
sets.add(new ArrayList<>(Arrays.asList(element)));
}
sets.add(new ArrayList<>());
return sets;
}
Input: [A, B, C]
Output: [[A], [A, C], [A, B], [A, B, C], [B], [B, C], [C], []]