Last active
April 29, 2020 15:40
-
-
Save zeitan/288fd9254cd42d60714b0c92f13626f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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