1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| public class Combinaisons {
public static void main(String[] args) {
String[] input = {
"those , the",
"accidents , connection",
"petroleum , tankers",
};
List<List<String>> liste = new ArrayList<>();
for(String ligne : input) {
liste.add( Arrays.asList(ligne.split("\\s*,\\s*")) );
}
List<String> combinaisons = createCombinaisons(liste);
for(String combinaison : combinaisons) {
System.out.println(combinaison);
}
}
public static List<String> createCombinaisons(List<List<String>> liste) {
List<String> combinaisons = new ArrayList<>();
createCombinaisons(liste, combinaisons, new Stack<Integer>(), new StringBuilder());
return combinaisons;
}
private static void createCombinaisons(List<List<String>> liste,
List<String> combinaisons, Stack<Integer> indexList,
StringBuilder stringBuilder) {
// la taille courante de la pile correspond au niveau de boucle imbriquée courant
if ( indexList.size()<liste.size() ) {
List<String> ligne = liste.get(indexList.size());
// on stocke l'itération sur la ligne courante en utilisant une pile, ce qui permet
// de simuler n boucles imbriquées
for(int i=0; i<ligne.size(); i++) {
indexList.push(i);
createCombinaisons(liste, combinaisons, indexList, stringBuilder);
indexList.pop();
}
}
else {
// combinaison des indices de boucle, correspondant à la dernière boucle imbriquée
for(int i=0; i<indexList.size(); i++) {
// boucle imbriquée de niveau i
if ( i>0 ) {
stringBuilder.append(" - ");
}
List<String> ligne = liste.get(i); // liste de mot de niveau i
int indexMot = indexList.get(i); // valeur actuelle de l'indice de la boucle de niveau i
String mot = ligne.get(indexMot); // mot correspondant
stringBuilder.append(mot);
}
combinaisons.add(stringBuilder.toString()); // on stocke la combinaison trouvée
stringBuilder.setLength(0); // on recycle le StringBuilder
}
}
} |
Partager