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

How do I do the product of a matrix of string in Java?

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

我想为每个数组中的每个值创建 "product"(或串联)。

例子

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

我做到了并且效果很好。

private static List<String> multiply(List<String> x, List<String> y) {
    List<String> results = new ArrayList<>();
    x.forEach(s1 -> y.forEach(s2 ->
                    results.add(s1+s2 )
            )
    );
    return results;
}

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

    for (int i = 0; i < inputs.size(); i++) {
        results = multiply(results, inputs.get(i));
    }
    System.out.println("results = " + results);

}

输出:

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