2

是否有与 Ruby 的 Array#product 方法等效的 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

4

1 回答 1

1

这是一个利用递归的解决方案。不知道你想要什么输出,所以我刚刚打印了产品。你也应该看看这个问题。

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);
        }
    }
}
于 2010-09-18T22:45:30.480 回答