Cartesian Product and java Algorithm Implementation
In mathematics, Two SetsXAndYCartesian product, also known as the straight productX×YThe first object isXAnd the second object isYAll possible sequential pairs of a member. Assume that the Set A = {a, B}, and set B = {0, 1}, the Cartesian product of the Two sets is {(a, 0), (a, 1 ), (a, 2), (B, 0), (B, 1), (B, 2 )}.
Java implementation:
- Import java. util. ArrayList;
- Import java. util. List;
- Public class Descartes
- {
- Public static void run (List <String> dimvalue, List <String> result, int layer, String curstring)
- {
- // When the value is greater than one set:
- If (layer <dimvalue. size ()-1)
- {
- // When the value is greater than one set, the first set is empty.
- If (dimvalue. get (layer). size () = 0)
- Run (dimvalue, result, layer + 1, curstring );
- Else
- {
- For (int I = 0; I <dimvalue. get (layer). size (); I ++)
- {
- StringBuilder s1 = new StringBuilder ();
- S1.append (curstring );
- S1.append (dimvalue. get (layer). get (I ));
- Run (dimvalue, result, layer + 1, s1.toString ());
- }
- }
- }
- // When there is only one set:
- Else if (layer = dimvalue. size ()-1)
- {
- // There is only one set with no elements in the Set
- If (dimvalue. get (layer). size () = 0)
- Result. add (curstring );
- // When there is only one set and the set contains elements: Its Cartesian product is the set element itself.
- Else
- {
- For (int I = 0; I <dimvalue. get (layer). size (); I ++)
- {
- Result. add (curstring + dimvalue. get (layer). get (I ));
- }
- }
- }
- }
- /**
- * @ Param args
- */
- Public static void main (String [] args)
- {
- List <String> dimvalue = new ArrayList <List <String> ();
- List <String> v1 = new ArrayList <String> ();
- V1.add ("");
- V1.add ("B ");
- List <String> v2 = new ArrayList <String> ();
- V2.add ("c ");
- V2.add ("d ");
- V2.add ("e ");
- List <String> v3 = new ArrayList <String> ();
- V3.add ("f ");
- V3.add ("g ");
- Dimvalue. add (v1 );
- Dimvalue. add (v2 );
- Dimvalue. add (v3 );
- List <String> result = new ArrayList <String> ();
- Descartes. run (dimvalue, result, 0 ,"");
- Int I = 1;
- For (String s: result)
- {
- System. out. println (I ++ ":" + s );
- }
- }
- }
Output result:
- 1:acf
- 2:acg
- 3:adf
- 4:adg
- 5:aef
- 6:aeg
- 7:bcf
- 8:bcg
- 9:bdf
- 10:bdg
- 11:bef
- 12:beg
Program instructions (1) treat the elements of each dimension set as List <string>, multiple sets constitute List <string> dimvalue as input (2) put the result of the multi-dimensional Cartesian product into the List <string> result as the output (3) int layer. string curstring is only a parameter of two intermediate processes carrying the variable (4). The program uses recursive calls, an example of the initial call is as follows: