diff options
Diffstat (limited to 'base/src/main/java/bjc/utils/funcutils/SetUtils.java')
| -rw-r--r-- | base/src/main/java/bjc/utils/funcutils/SetUtils.java | 24 |
1 files changed, 23 insertions, 1 deletions
diff --git a/base/src/main/java/bjc/utils/funcutils/SetUtils.java b/base/src/main/java/bjc/utils/funcutils/SetUtils.java index eac417c..d57ac00 100644 --- a/base/src/main/java/bjc/utils/funcutils/SetUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/SetUtils.java @@ -5,10 +5,21 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +/** + * Various utility functions dealing with sets. + * @author bjculkin + * + */ public class SetUtils { + /** + * Create a power-set (set of all subsets) of a given set. + * @param originalSet The set to create a power-set of. + * @return The power-set of the set. + */ public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { Set<Set<T>> sets = new HashSet<Set<T>>(); + // Special-case empty input if (originalSet.isEmpty()) { sets.add(new HashSet<T>()); return sets; @@ -16,13 +27,18 @@ public class SetUtils { List<T> list = new ArrayList<T>(originalSet); + // Add original set to list. T head = list.get(0); + // Trim leading element from set. Set<T> rest = new HashSet<T>(list.subList(1, list.size())); - for (Set<T> set : powerSet(rest)) { + Set<Set<T>> remSets = powerSet(rest); + + for (Set<T> set : remSets) { Set<T> newSet = new HashSet<T>(); + // Create a new set with the removed element. newSet.add(head); newSet.addAll(set); @@ -33,6 +49,12 @@ public class SetUtils { return sets; } + /** + * Utility method for set construction. + * @param elms The elements to stick in the set. + * @return A set containing the specified elements. + */ + @SafeVarargs public static <T> Set<T> toSet(T... elms) { Set<T> set = new HashSet<>(); |
