用位元串法求冪集的java實現

來源:互聯網
上載者:User

標籤:

由於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實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.