Search code examples
javaarraysalgorithmbrute-forcecartesian-product

Finding all possible combinations of elements of six arrays


I have 6 arrays, each has 8 elements. I'd like to write a method that reveals all the possible combinations of all the elements of all arrays like:

firstArray firstElement, secondArray firstElement,.... sixthArray firstElement

firstArray secondElement, secondArray firstElement,.... sixthArray firstElement

....etc...

firstArray lastElement, secondArray lastElement,.... sixthArray lastElement

How can I do this in the most efficient way, the most performance-friendly way?

for (int i = 0; i < A.length; i++) {
  for (int j = 0; j < B.length; j++) {
    for (int h = 0; h < C.length; h++) {
      for (int k = 0; k < D.length; k++) {
        for (int l = 0; l < E.length; l++) {
          for (int n = 0; n < F.length; n++) {
            System.out.println(A[i] + " "
                             + B[j] + " "
                             + C[h] + " "
                             + D[k] + " "
                             + E[l] + " "
                             + F[n]);
          }
        }
      }
    }
  }
}

Solution

  • Simplest Code would be:

    for (first array a) {
      for (second array b) {
        for (third array c) {
          for (fourth array d) {
            for (fifth array e) {
              for (sixth array f) {
                System.out.println(a[], b[], c[], d[], e[], f[]);
              }
            }
          }
        }
      }
    }
    

    This is not good performance wise as it will take - no. of arrays * element per array * element per array time.