edu.stanford.nlp.util.Sets Maven / Gradle / Ivy
package edu.stanford.nlp.util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Utilities for sets.
*
* @author Roger Levy, Bill MacCartney
*/
public class Sets {
// private to prevent instantiation
private Sets() {}
/**
* Returns the set cross product of s1 and s2, as Pair
s
*/
public static Set> cross(Set s1, Set s2) {
Set> s = new HashSet>();
for (E o1 : s1) {
for (F o2 : s2) {
s.add(new Pair(o1, o2));
}
}
return s;
}
/**
* Returns the difference of sets s1 and s2.
*/
public static Set diff(Set s1, Set s2) {
Set s = new HashSet();
for (E o : s1) {
if (!s2.contains(o)) {
s.add(o);
}
}
return s;
}
/**
* Returns the symmetric difference of sets s1 and s2 (i.e. all elements that are in only one of the two sets)
*/
public static Set symmetricDiff(Set s1, Set s2) {
Set s = new HashSet();
for (E o : s1) {
if (!s2.contains(o)) {
s.add(o);
}
}
for (E o : s2) {
if (!s1.contains(o)) {
s.add(o);
}
}
return s;
}
/**
* Returns the union of sets s1 and s2.
*/
public static Set union(Set s1, Set s2) {
Set s = new HashSet();
s.addAll(s1);
s.addAll(s2);
return s;
}
/**
* Returns the intersection of sets s1 and s2.
*/
public static Set intersection(Set s1, Set s2) {
Set s = new HashSet();
s.addAll(s1);
s.retainAll(s2);
return s;
}
/**
* Returns true if there is at least element that is in both s1 and s2. Faster
* than calling intersection(Set,Set) if you don't need the contents of the
* intersection.
*/
public static boolean intersects(Set s1, Set s2) {
// loop over whichever set is smaller
if (s1.size() < s2.size()) {
for (E element1 : s1) {
if (s2.contains(element1)) {
return true;
}
}
} else {
for (E element2 : s2) {
if (s1.contains(element2)) {
return true;
}
}
}
return false;
}
/**
* Returns the powerset (the set of all subsets) of set s.
*/
public static Set> powerSet(Set s) {
if (s.isEmpty()) {
Set> h = new HashSet>();
Set h0 = new HashSet(0);
h.add(h0);
return h;
} else {
Iterator i = s.iterator();
E elt = i.next();
s.remove(elt);
Set> pow = powerSet(s);
Set> pow1 = powerSet(s);
// for (Iterator j = pow1.iterator(); j.hasNext();) {
for (Set t : pow1) {
// Set t = new HashSet((Set) j.next());
t.add(elt);
pow.add(t);
}
s.add(elt);
return pow;
}
}
public static void main(String[] args) {
Set h = new HashSet();
h.add("a");
h.add("b");
h.add("c");
Set> pow = powerSet(h);
System.out.println(pow);
}
}