Given:
input
String.N
How can I generate all possible words that has the exact length of N?
If I have input = {"a", "b", "a"}
and N=2
, then the output should be: ab,aa,ba
(without the duplicates)
I searched for this, and all I got is some algorithms that I couldn't understand rather that implement. I understand that I need to implement a recursive method, but I'm stuck at the point after the stop condition.
public void generate(String input, int length) {
if(length == 0) {
System.out.println(input);
return;
}
//Not sure about this part
String[] a = input.split("");
for(int i =0; i<a.length; i++) {
loop(input+a[i], length-1);
}
}
This should do the trick and work with any input
and N
. Behavior is not well defined for N = 0
or N > input.length()
public static void generate(String input, int N) {
generate("", input, new HashSet<String>(), N);
}
private static void generate(String str, String input, Set<String> dup, int N) {
if (str.length() == N && dup.add(str))
System.out.println(str);
else
//remove a char form input and add it to str
for (int i = 0; i < input.length(); i++)
generate(
str + input.charAt(i),
input.substring(0, i) + input.substring(i + 1),
dup, N);
}
This has been adapted from the more general "calculate all permutation" problem. In the general problem there is no duplicate check and str
is printed when input.isEmpty()
. Let me know if you need any clarifications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With