本文轉載於: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