Skip to content

Instantly share code, notes, and snippets.

@zeitan
Last active April 29, 2020 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeitan/288fd9254cd42d60714b0c92f13626f1 to your computer and use it in GitHub Desktop.
Save zeitan/288fd9254cd42d60714b0c92f13626f1 to your computer and use it in GitHub Desktop.
private static Set<Set<Integer>> calculatePowerSet(Set<Integer> list) {
int size = list.size();
Set<Set<Integer>> powerSet = new HashSet<>();
powerSet.add(Collections.EMPTY_SET);
if (size == 0) {
return powerSet;
}
Integer[] elems = list.toArray(new Integer[size]);
int end = (int) Math.pow(2, size) - 1;
for (int i=1; i<= end; i++) {
boolean[] bits = calculateBits(i);
Set<Integer> setElems = new HashSet<>();
for(int j = 0; j < size; j++ ) {
if(bits[j]) {
setElems.add(elems[j]);
}
}
powerSet.add(setElems);
}
return powerSet;
}
private static boolean[] calculateBits(int number) {
boolean[] bits = new boolean[32];
for (int i = 31; i >= 0; i--) {
bits[i] = (number & (1 << i)) != 0;
}
return bits;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment