简体   繁体   中英

Combination of a matrix of arrays of variable length

I have to obtain all possibile combination of this kind of matrix:

String[][] matrix = {
   {"AA-123", "AA-124", "AA-125", "AA-126"},
   {"BB-12", "BB-13"},
   {"CC-1"},
};

After all, that is the final implementation. It's in Java, but the language may be irrilevant:

long nComb = 1;
for (int iMatr = 0; iMatr < matrix.length; iMatr++)
   nComb *= matrix[iMatr].length;

for (int iComb = 0; iComb < nComb; iComb++) {
   System.out.print("|");

   long nSec = 1;
   for (int iSec = 0; iSec < matrix.length; iSec++) {
       String[] sec = matrix[iSec];

       for (int iAtom = 0; iAtom < sec.length; iAtom++) {

           if (iAtom == ((iComb / nSec) % sec.length))
               System.out.print(1);
           else
               System.out.print(0);
       }

       nSec *= sec.length;
       System.out.print("|");
   }

   System.out.println();
}

I have to apply my logic on the if that it prints 1 or 0. I need to know what is the current element (index) of the combination of the array. The expected result:

|1000|10|1|
|0100|10|1|
|0010|10|1|
|0001|10|1|
|1000|01|1|
|0100|01|1|
|0010|01|1|
|0001|01|1|

Regards.

Edit:

I find a possible answer using another variable in the array iteration: nSec . It product increse by the lenght of the array over iterations, reaching at the last iteration the value of nComb .

I believe what you're after here is called the cartesianProduct of the multiple collections and this is already supported by a number of collection libraries in Java.

Personally I'd recommend using Guava ( https://code.google.com/p/guava-libraries/ ) which will allow you to define your problem as follows (conversion between Array and Set I will leave out as an exercise :):

import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;

public class CartesianProduct {

    public static void main(String[] args) {
        Set<List<String>> merged = Sets.cartesianProduct(
                Sets.newHashSet("AA-123", "AA-124", "AA-125", "AA-126"),
                Sets.newHashSet("BB-12", "BB-13"),
                Sets.newHashSet("CC-1")
        );
        System.out.println("Size: " + merged.size());
        System.out.println("Content: " + merged);
    }

}

By executing this code you will get the following result:

Size: 8
Content: [
   [AA-125, BB-13, CC-1], 
   [AA-125, BB-12, CC-1], 
   [AA-124, BB-13, CC-1], 
   [AA-124, BB-12, CC-1], 
   [AA-123, BB-13, CC-1], 
   [AA-123, BB-12, CC-1], 
   [AA-126, BB-13, CC-1], 
   [AA-126, BB-12, CC-1]
]

Then further you can process, sort and format output the way you require (and when printing it another guava class Joiner might come handy).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM