The implementation of __java algorithm based on the Java algorithm of Cartesian product

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.