笛卡兒積的Java演算法實現__java演算法

來源:互聯網
上載者:User
本文轉載於:http://xiemingmei.iteye.com/blog/1484587

笛卡爾積演算法的Java實現:

(1)迴圈內,每次只有一列向下移一個儲存格,就是CounterIndex指向的那列。
(2)如果該列到尾部了,則這列index重設為0,而CounterIndex則指向前一列,相當於進位,把前列的index加一。
(3)最後,由產生的行數來控制退出迴圈。

1.public class Test {  2.  3.    private static String[] aa = { "aa1", "aa2" };  4.    private static String[] bb = { "bb1", "bb2", "bb3" };  5.    private static String[] cc = { "cc1", "cc2", "cc3", "cc4" };  6.    private static String[][] xyz = { aa, bb, cc };  7.    private static int counterIndex = xyz.length - 1;  8.    private static int[] counter = { 0, 0, 0 };  9.  10.    public static void main(String[] args) throws Exception {  11.  12.        for (int i = 0; i < aa.length * bb.length * cc.length; i++) {  13.            System.out.print(aa[counter[0]]);  14.            System.out.print("\t");  15.            System.out.print(bb[counter[1]]);  16.            System.out.print("\t");  17.            System.out.print(cc[counter[2]]);  18.            System.out.println();  19.  20.            handle();  21.        }  22.    }  23.  24.    public static void handle() {  25.        counter[counterIndex]++;  26.        if (counter[counterIndex] >= xyz[counterIndex].length) {  27.            counter[counterIndex] = 0;  28.            counterIndex--;  29.            if (counterIndex >= 0) {  30.                handle();  31.            }  32.            counterIndex = xyz.length - 1;  33.        }  34.    }  35.  36.}  


輸出共2*3*4=24行:
aa1 bb1 cc1
aa1 bb1 cc2
aa1 bb1 cc3
aa1 bb1 cc4
aa1 bb2 cc1
aa1 bb2 cc2
aa1 bb2 cc3
aa1 bb2 cc4
aa1 bb3 cc1
aa1 bb3 cc2
aa1 bb3 cc3
aa1 bb3 cc4
aa2 bb1 cc1
aa2 bb1 cc2
aa2 bb1 cc3
aa2 bb1 cc4
aa2 bb2 cc1
aa2 bb2 cc2
aa2 bb2 cc3
aa2 bb2 cc4
aa2 bb3 cc1
aa2 bb3 cc2
aa2 bb3 cc3
aa2 bb3 cc4

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.