2010-09-18 114 views
2

可变数量的产品是有一个Java等同于Ruby的数组#产品的方法,或这样做的方式:查找字符串数组中的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

回答

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); 
     } 
    } 
} 
+0

非常好,谢谢。 – 2010-09-20 11:56:39