我想生成一个数组,其内容将表示两个给定字符串数组中的Cartesian product个.

换句话说,我需要将第一个数组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:

[cf, cf, cf, cf, cf, cf, cf, cf, cf]

Desired Output:

[ad, ae, af, bd, be, bf, cd, ce, cf]

我怎么才能修好它?

推荐答案

您不需要第一个for循环,它会导致结果数组中的所有值被多次覆盖.

相反,您需要在生成两个给定数组的笛卡尔乘积的nested loop之外声明结果数组的索引k.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:

[ad, ae, af, bd, be, bf, cd, ce, cf]

Java相关问答推荐

我应该避免在Android中创建类并在运行时编译它们吗?

如何在返回bigint []值的子查询中使用any?

Java List with all combinations of 8 booleans

Com.example.service.QuestionService中的构造函数的参数0需要找不到的类型为';com.example.Dao.QuestionDao;的Bean

使用Spring和ActiveMQ的侦听器方法引发属性名称不能重复为空警告

使用OAuth 2.0资源服务器JWT时的授权(授权)问题

try 将JSON字符串响应从API转换为映射字符串、对象>;时出错

为什么Collectors.toList()不能保证易变性

Java中不兼容的泛型类型

错误:未找到扩展元素在JBossEAP 7.2中安装FUSE时出错

为了安全起见,有必要复制一份 list 吗?

在实例化中指定泛型类型与不指定泛型类型之间的区别

在Eclipse中可以使用外部字体吗?

如何在Maven Central上部署?

Java List有一个在一个位置添加多个元素的方法,但我找不到一个在一个位置删除多个元素的方法

Java CDI:@Singleton@Startup@Inject无法实现接口

如何修复Spring Boot应用程序中的RestDocumentationGenerationException:java.io.FileNotFoundException:/curl-request.adoc(只读文件系统)?

Java中计算大n和k值模10^9+7的二项式系数的乘法公式输出错误值

在外部类和内部类之间,当调用外部类内部或外部的主方法时,它们的静态初始化程序的运行顺序不同

为什么 log4j 过滤器在appender中不起作用