在Java中查找可变数量的字符串数组的乘积

时间:2010-09-18 19:11:26

标签: java arrays string product

是否存在类似于Ruby的Array#产品方法的Java,或者这样做的方法:

groups = [
  %w[hello goodbye],
  %w[world everyone],
  %w[here there]
]

combinations = groups.first.product(*groups.drop(1))

p combinations
# [
#   ["hello", "world", "here"],
#   ["hello", "world", "there"],
#   ["hello", "everyone", "here"],
#   ["hello", "everyone", "there"],
#   ["goodbye", "world", "here"],
#   ["goodbye", "world", "there"],
#   ["goodbye", "everyone", "here"],
#   etc.

这个问题是这个问题的Java版本:Finding the product of a variable number of Ruby arrays

1 个答案:

答案 0 :(得分:1)

这是一个利用递归的解决方案。不确定你输出的是什么,所以我刚打印出产品。您还应该查看this问题。

public void printArrayProduct() {
    String[][] groups = new String[][]{
                                   {"Hello", "Goodbye"},
                                   {"World", "Everyone"},
                                   {"Here", "There"}
                        };
    subProduct("", groups, 0);
}

private void subProduct(String partProduct, String[][] groups, int down) {
    for (int across=0; across < groups[down].length; across++)
    {
        if (down==groups.length-1)  //bottom of the array list
        {
            System.out.println(partProduct + " " + groups[down][across]);
        }
        else
        {
            subProduct(partProduct + " " + groups[down][across], groups, down + 1);
        }
    }
}