-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathPowerSet.java
More file actions
56 lines (49 loc) · 1.65 KB
/
PowerSet.java
File metadata and controls
56 lines (49 loc) · 1.65 KB
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
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class PowerSet {
public static final <E> Collection<Set<E>> of(Set<E> s) {
List<E> src = new ArrayList<>(s);
if (src.size() > 30) {
throw new IllegalArgumentException("Set too big " + s);
}
return new AbstractCollection<Set<E>>() {
@Override
public int size() {
return 1 << src.size();
}
@Override
public boolean contains(Object o) {
return o instanceof Set && src.containsAll((Set) o);
}
@Override
public Iterator<Set<E>> iterator() {
return new Iterator<Set<E>>() {
private int index = 0;
private int end = size();
@Override
public boolean hasNext() {
return index < end;
}
@Override
public Set<E> next() {
Set<E> result = new HashSet<>();
for (int i = 0, j = index; j != 0; i++, j >>= 1) {
if ((j & 1) == 1) {
result.add(src.get(i));
}
}
index++;
return result;
}
};
}
};
}
public static void main(String[] args) {
Set<Character> set = Set.of('a', 'b', 'c');
for (Set<Character> s : PowerSet.of(set)) {
System.out.println(s);
}
}
}