2010-09-18 9 views
2

Y at-il un équivalent Java à matrice méthode de # produit Ruby, ou une façon de le faire:Trouver le produit d'un nombre variable de tableaux de chaînes en 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. 

Cette question est une version Java de celle-ci : Finding the product of a variable number of Ruby arrays

Répondre

1

Voici une solution qui tire parti de la récursivité. Vous ne savez pas quelle sortie vous cherchez, alors je viens d'imprimer le produit. Vous devriez également vérifier 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); 
     } 
    } 
} 
+0

Brillant, merci. –