Because Java has a convenient String integer.tobinarystring (int), when learning to generate a subset of the algorithm to generate a power set with a bit string, think of Java implementation. Power set is very useful when solving knapsack problem, brute force method, simple and rough effective, of course, limited to small examples.
Implement the following Powersetgenerator.java, where the implementation of the container is linkedhashset to ensure that the position of the elements in the collection is fixed for easy testing:
package powerset;import java.util.collection;import java.util.linkedhashset;import java.util.iterator;public class powersetgenerator<t> {public collection< Collection<t>> getpowerset (Collection<t> set) {collection<collection<t>> r = new LinkedHashSet<Collection<T>> ();int binary = 1<< Set.size (); for (int i=0;i<binary;i++) {R.add (Getsubset (Set,i));} Return r;} Private collection<t> getsubset (collection<t> set,int binaryseq) {Collection <T> sub = new LinkedHashSet<T> ();int mask = 1 << set.size (); Iterator<t> it = set.iterator (); while (It.hasnext ()) {t obj = it.next (); Mask >>>= 1;if ((Binaryseq & mask)!=0) {sub.add (obj);}} Return sub;}}
The
Groovy unit test powersettest.groovy is quite handy, especially for building collections:
package powerset;import static org.junit.assert.*;import org.junit.test;class Powersettest {static def set = [' A ', ' B ', ' C ']static def result = [ [], [' C '], [' B '], [' B ', ' C '], [' a '], [' a ', ' C '], [' a ', ' B '], [' A ', ' B ', ' C ']]static def set2 = [1,2,3,4]static def result2 = [[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, &NBSP;3,&NBSP;4],&NBSP;[1],&NBSP;[1,&NBSP;4],&NBSP;[1,&NBSP;3],&NBSP;[1,&NBSP;3,&NBSP;4],&NBSP;[1,&NBSP;2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]static def SET3&NBSP;=&NBSP;[1]STATIC&NBSP;DEF&NBSP;RESULT3&NBSP;=&NBSP;[[],&NBSP;[1]] @Testpublic void test () {PowerSetGenerator<Integer> generator = new PowerSetGenerator<Integer> () ; Assertequals (Result.tostring (), GEnerator.getpowerset (set). ToString ()); Assertequals (Result2.tostring (), Generator.getpowerset (Set2). ToString ()); Assertequals (Result3.tostring (), Generator.getpowerset (Set3). toString ());}}
Java implementation of power set using bit-string method