This article is reproduced in: http://xiemingmei.iteye.com/blog/1484587
the Java implementation of the Cartesian product algorithm:
(1) within a loop, only one column moves down one cell at a time, which is the column that Counterindex points to.
(2) If the column to the tail, then this column index reset to 0, and Counterindex refers to a column forward, equivalent to carry, the front of the index plus one.
(3) Finally, the exit loop is controlled by the number of rows generated.
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. for (int i = 0; i < aa.length * Bb.length * cc.length; i++) {13.
System.out.print (Aa[counter[0]]);
System.out.print ("T");
System.out.print (bb[counter[1]);
System.out.print ("T");
System.out.print (Cc[counter[2]]);
System.out.println (); 19.20.
Handle (); 21.} 22.
} 23. public static void handle () {25.
counter[counterindex]++; if (Counter[counterindex] >= xyz[Counterindex].length) {27.
Counter[counterindex] = 0;
counterindex--; if (counterindex >= 0) {30.
Handle (); 31.} 32.
Counterindex = xyz.length-1; 33.} 34.
} 35.
36.}
Output total 2*3*4=24 rows:
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