Finding the product of a variable number of string arrays in Java
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"],
# ["hell开发者_开发技巧o", "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
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);
}
}
}
精彩评论