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: Finding the product of a variable number of Ruby arrays

Community
  • 1
  • 1
Ollie Glass
  • 19,455
  • 21
  • 76
  • 107

1 Answers1

1

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);
        }
    }
}
Community
  • 1
  • 1
Chris Knight
  • 24,333
  • 24
  • 88
  • 134