A subset of a N-sized set can be represented with an N-bit binary number, where each bit determines whether or not the subset contains its corresponding member. By incrementing the binary representation we can easily iterate over all the possible subsets.
Here is a simple implementation:
publicstatic<T>Set<Set<T>>powerSet(Set<T>set){// We need to have them ordered, to match the bits of the binary rep.ArrayList<T>values=newArrayList<>(set);boolean[]binaryRep=newboolean[values.size()];Set<Set<T>>powerSet=newHashSet<>();while(true){Set<T>subset=createSubset(binaryRep,values);powerSet.add(subset);if(increment(binaryRep)){// Iterated over all the numbers.break;}}returnpowerSet;}privatestatic<T>Set<T>createSubset(boolean[]binaryRep,List<T>values){Set<T>subset=newHashSet<>();for(inti=0;i<binaryRep.length;++i){if(binaryRep[i]){subset.add(values.get(i));}}returnsubset;}privatestaticbooleanincrement(boolean[]binaryRep){for(inti=0;i<binaryRep.length;++i){if(binaryRep[i]){// Make the 1 bit a 0 and carry the 1.binaryRep[i]=false;}else{// Finally reached a 0 bit - set it to 1 and we are done.binaryRep[i]=true;returnfalse;}}// All the bits were 1 and we turned them to 0 - that means we "overflowed".returntrue;}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A subset of a N-sized set can be represented with an N-bit binary number, where each bit determines whether or not the subset contains its corresponding member. By incrementing the binary representation we can easily iterate over all the possible subsets.
Here is a simple implementation: