I have to create an algorithm which shows all the available unordered sequences of fixed lengths using a String array. The method needs to be recursive and may only take one integer. It also needs to return a String array.
Let's say I have "ab" and "ba". The following unordered sequences of fixed lenghts should be found when I'm giving the int 2 with the method:
abab
abba
baba
baab
I've been working for hours now and I have the feeling that I'm working way too hard for this simple thing. I have had different kinds of code and I had it almost working (abba was shown twice instead of another sequence) but I forgot to return it in an array so that caused problems... The code I have looks like this, but is unfinished and doesn't work:
static String[] syllables = {"ab", "ba"};
static String[] syllableWord;
public static void main(String[] args) {
int amountOfSillables = 2;
syllableWord = String[(int)Math.pow(amountOfSillables, amountOfSillables)];
String[] syllableWords = findSequences(amountOfSillables); // I may only use one parameter,
// which is 2 but should work with any number
for (int i = 0; i < syllableWords.length; i++) {
System.out.println(syllableWords[i]);
}
}
public static String[] findSequences(int n) {
if (n == 0) {
return syllableWord;
}
else {
for (int i = 0; i < syllables.length; i++) {
syllableWord += syllables[i]; // Doesn't work because syllableWord is an array.
// When it's a String this would kinda work, but it
// needs to be an array.
findSequences(n - 1);
syllableWord = syllableWord.substring(2); // Also doesn't work when it's an array.
}
}
}
Can somebody help me out? This is driving me crazy...