Reputation: 1939
I would like to see how to get the following output by using a Java recursive function. Would be great to get some insight on how to go about solving a problem like this. The recursive Java function should take these words: "MIKE", "AND", "IKE"
and output each ordering on a separate line such as this.
MIKEANDIKE
MIKEIKEAND
IKEANDMIKE
IKEMIKEAND
ANDIKEMIKE
ANDMIKEIKE
public static void main(String[] args) {
recur(new String[]{"MIKE", "AND", "IKE"}, "", 0);
}
public static void recur(String[] words, String result, int n) {
if (n == words.length) {
System.out.println(result);
return;
}
for (int i = 0; i < words.length; ++i) {
String out = result + words[i];
recur(words, out, n + 1);
}
}
Upvotes: 0
Views: 119
Reputation: 1445
You need to flag in some way the values that you have already used, in this example I use the null for that purpose, but there are other approaches to it (for example using a list and deleting/adding the values, or duplicating the lists themselves).
public static void recur(String[] words, String result, int n) {
if (n == words.length) {
System.out.println(result);
return;
}
String temp;
for (int i = 0; i < words.length; ++i) {
if (null != words[i]) {
String out = result + words[i];
temp = words[i];
words[i] = null;
recur(words, out, n + 1);
words[i] = temp;
}
}
}
Upvotes: 1
Reputation: 2375
The main thing to keep in mind is that you need to keep a state variable to decide the combination to print in each recursive call.
For example, the state variable could be a 3 digit number i.e. 123. And then map these digits with the words, for example, 1 is "MIKE", 2 is "AND", 3 is "IKE". So if the function is called with 123 then you would print "MIKEANDIKE", and then call again with next permutation of 123 which is 132 and so on.
I just mentioned one possible state variable variation. There could be countless way to declare a state variable. The main idea you can get from this is an idea of how you can approach to solve the problem.
Hope this helps! Let me know if don't understand anything. Happy coding!
Upvotes: 0