gpt4 book ai didi

java - 如何在 Java 中计算字符串矩阵的乘积?

转载 作者:行者123 更新时间:2023-11-30 06:30:08 24 4
gpt4 key购买 nike

我有未知数量的 String[]。每个数组可以有不同的大小。

我想创建每个数组中每个值的“乘积”(或串联)。

示例

public static void main(String[] args) {
String[] x = {"a", "b", "c"};
String[] y = {"d", "e", "f", "g"};
String[] z = {"h", "i"};
...
}

期望的输出

输出将是adh, adi, aeh, aei, ...

我认为我必须通过递归来处理这个问题,因为我不知道我有多少个数组。但即便如此,我还是很难找到将结果存储在哪里。

有什么指点吗?

最佳答案

好的,我找到了方法

package eu.webfarmr;

import java.util.ArrayList;
import java.util.List;

public class Dummy {
public static void main(String[] args) {
String[] x = {"a", "b", "c"};
String[] y = {"d", "e", "f", "g"};
String[] z = {"h", "i"};
ArrayList<String[]> list = new ArrayList<String[]>();
list.add(x);
list.add(y);
list.add(z);
List<String> result = product(list);
for (String r : result){
System.out.println(r);
}
}

private static ArrayList<String> product(ArrayList<String[]> items){
ArrayList<String> result = new ArrayList();
if (items!=null && items.size()>0){
String[] currentItem = items.get(0);
ArrayList<String[]> clone = (ArrayList<String[]>) items.clone();
clone.remove(0);
for (String item : currentItem){
ArrayList<String> product = product(clone);
if (product!=null && product.size()>0){
for (String p : product){
result.add(item+p);
}
} else {
result.add(item);
}
}
}
return result;
}
}

此代码将输出

adh
adi
aeh
aei
afh
afi
agh
agi
bdh
bdi
beh
bei
bfh
bfi
bgh
bgi
cdh
cdi
ceh
cei
cfh
cfi
cgh
cgi

关于java - 如何在 Java 中计算字符串矩阵的乘积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com