標籤:
由於Java中有很方便的 String Integer.toBinaryString(int),在學習產生子集的時後看到用位元串產生冪集的演算法,就想著用java實現一下。冪集在解背包問題的時候還是很有用的,蠻力法,簡單粗暴有效,當然僅限較小的執行個體。
實現如下 PowerSetGenerator.java,其中容器的實現用LinkedHashSet是為了保證集合中元素的位置固定,方便測試:
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;}}
groovy單元測試 PowerSetTest.groovy,相當方便,特別是構建集合:
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, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]static def set3 = [1]static def result3 = [[], [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實現