views:

43

answers:

2

Is there a Java equivalent to Ruby's Array#product method, or a way of doing this:

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.

This question is a Java version of this one: http://stackoverflow.com/questions/3419952/finding-the-product-of-a-variable-number-of-ruby-arrays

+1  A: 

This thread might help you out

letronje
+1  A: 

Here's a solution which takes advantage of recursion. Not sure what output you're after, so I've just printed out the product. You should also check out this question.

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);
        }
    }
}
Chris Knight
Brilliant, thank you.
Ollie G