Created
March 26, 2013 18:48
-
-
Save tmarthal/5248035 to your computer and use it in GitHub Desktop.
PowerSet Calculation in java
This file contains hidden or 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
import java.util.HashSet; | |
import java.util.Set; | |
public class PowerSet { | |
private Set<Set<Object>> powerSet; | |
private void setCombinations(Set<Object> set) { | |
powerSet.add(set); | |
if (set != null && !set.isEmpty()) { | |
for (Object obj : set) { | |
Set<Object> setWithoutObj = new HashSet<Object>(); | |
setWithoutObj.addAll(set); | |
setWithoutObj.remove(obj); | |
if (powerSet.contains(setWithoutObj)) { | |
continue; | |
} else { | |
setCombinations(setWithoutObj); | |
} | |
System.out.println("leftSet " + set); | |
} | |
} | |
} | |
public String toString() { | |
return powerSet.toString(); | |
} | |
public PowerSet(Set<Object> objects) { | |
powerSet = new HashSet<Set<Object>>(); | |
// Calculate combinations with the original and the empty set | |
setCombinations(objects); | |
} | |
public static void main(String[] args) { | |
Set s = new HashSet(); | |
s.add("a"); | |
s.add("b"); | |
s.add("c"); | |
PowerSet p = new PowerSet(s); | |
System.out.println(p); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment