String[] test = { "la", "li", "lo" };
language(3, test);
private String language(int n, String[] syllables) { // example of N = 3
for (int i = 0; i < syllables.length; i++) {
String w1 = syllables[i];
for (int j = 0; j < syllables.length; j++) {
String w2 = syllables[j];
for (int x = 0; x < syllables.length; x++) {
String w3 = syllables[x];
System.out.println(w1 + w2 + w3);
}
}
}
}
I'm trying to create a recursive method that can create any form of the String array. But I'm unable to achieve this
Variables
n = amount of syllables
syllables = String Array of the base words
Output
lalala
lalali
lalalo
lalila
lalili
lalolo
lilala
lolala
lilili
lololo
......
This will give you the result you are expecting:
String[] test = { "la", "li", "lo" };
language(3, test, "");
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
You'd need something along these lines:
private void recursiveMethod(int numberOfSyllablesToAdd, String[] syllables, String word) {
for (int i = 0; i < syllables.length; i++) {
String newWord = word + syllables[i];
if (numberOfSyllablesToAdd >= 0) {
recursiveMethod(numberOfSyllablesToAdd - 1, syllables, newWord);
} else {
System.out.println(newWord);
}
}
}
Note: This is really ineffective for multiple reasons (like not using a StringBuilder or StringBuffer to create the words)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.