有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

是否有一种Java等效于Ruby的Array#product方法,或者有一种方法可以做到这一点:

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) 个答案

  1. # 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);
            }
        }
    }