summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/funcutils/SetUtils.java
blob: 83c191bde4b1d3d06fe5a5b35a46697f2a56a500 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package bjc.utils.funcutils;

import java.util.ArrayList;
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<>();

		// Special-case empty input
		if (originalSet.isEmpty()) {
			sets.add(new HashSet<T>());
			return sets;
		}

		List<T> list = new ArrayList<>(originalSet);

		// Add original set to list.
		T head = list.get(0);

		// Trim leading element from set.
		Set<T> rest = new HashSet<>(list.subList(1, list.size()));

		Set<Set<T>> remSets = powerSet(rest);

		for (Set<T> set : remSets) {
			Set<T> newSet = new HashSet<>();

			// Create a new set with the removed element.
			newSet.add(head);
			newSet.addAll(set);

			sets.add(newSet);
			sets.add(set);
		}

		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<>();

		for (T elm : elms) {
			set.add(elm);
		}

		return set;
	}
}