I want to generate an array which content would represent a Cartesian product of the two given string-arrays.
In other words, I need to concatenate each String
from the first array arr1
with every String
from the second array arr2
.
Here is my code:
String[] arr1 = {"a", "b", "c"};
String[] arr2 = {"d", "e", "f"};
String[] result = new String[arr1.length * arr2.length];
for (int k = 0; k < result.length; k ) {
for (int i = 0; i <arr1.length; i ) {
for (int j = 0; j < arr2.length; j ) {
result[k] = arr1[i] arr2[j];
}
}
}
System.out.println(Arrays.toString(result));
Current Output:
[cf, cf, cf, cf, cf, cf, cf, cf, cf]
Desired Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]
How can I fix it?
CodePudding user response:
You don't need the very first for
-loop, it causes all the values in the resulting array to be overwritten multiple times.
Instead, you need to declare the index k
of the resulting array outside the nested loop that generates the Cartesian product of the two given arrays. k
should be incremented at each iteration step of the inner loop.
int k = 0;
for (int i = 0; i < arr1.length; i ) {
for (int j = 0; j < arr2.length; j ) {
result[k ] = arr1[i] arr2[j];
}
}
System.out.println(Arrays.toString(arr3));
Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]