[英]Fill the Third Array by adding the elements of the First and Second Arrays
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
.换句话说,我需要将第一个数组arr1
中的每个String
与第二个数组arr2
中的每个String
连接起来。
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:当前 Output:
[cf, cf, cf, cf, cf, cf, cf, cf, cf]
Desired Output:所需的 Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]
How can I fix it?我该如何解决?
You don't need the very first for
-loop, it causes all the values in the resulting array to be overwritten multiple times.您不需要第一个for
循环,它会导致结果数组中的所有值被多次覆盖。
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.相反,您需要在生成两个给定 arrays 的笛卡尔积的嵌套循环之外声明结果数组的索引k
。 k
should be incremented at each iteration step of the inner loop. k
应该在内循环的每个迭代步骤中递增。
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: Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.