Having a problem, only printing one instead of each powerset and I can't quite spot it. Trying to write a program that gives out a powerset of a given set.
import java.util.HashSet;
import java.util.Iterator;
public class PowerSet {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
HashSet<HashSet<String>> powerset;
set.add("a");
set.add("b");
set.add("c");
set.add("d");
powerset = powerset(set);
System.out.println(powerset);
}
public static HashSet<HashSet<String>> powerset( HashSet<String> set){
if (set.size()== 0) {
HashSet<HashSet<String>> pset = new HashSet<HashSet<String>>();
HashSet<String> emptySet = new HashSet<String>();
pset.add(emptySet);
return pset;
} else {
HashSet<String> tmp;
Iterator<String> it = set.iterator();
String elt = it.next();
set.remove(elt);
HashSet<HashSet<String>> oldpset = powerset(set);
HashSet<HashSet<String>> newpset = new HashSet<HashSet<String>>();
Iterator<HashSet<String>> psetit = oldpset.iterator();
while(psetit.hasNext()){
tmp = psetit.next();
newpset.add(tmp);
tmp.add(elt);
newpset.add(tmp);
}
return newpset;
}
}
}
One issue I see is that you remove the element elt
from set
before calling powerset(set)
. Because Java objects act as pointers, when you remove an element from set at for the current call to powerset
, you are modifying all references to it (even references stored on the stack from previous calls).
Another issue I see is that you use set.remove(elt)
, you should be using it.remove()
or you will mess up the iterator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.