Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate All Possible Words of Length n [duplicate]

Tags:

java

Given:

  • Some characters in input String.
  • An integer 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);
    }
}
like image 868
iTurki Avatar asked Nov 13 '22 01:11

iTurki


1 Answers

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.

like image 164
Marsellus Wallace Avatar answered Nov 15 '22 13:11

Marsellus Wallace