-7

I've got to make all possible anagram string combinations with java. Checking whether two strings are anagram or not is not my problem.. But when it comes to generating the whole set of possible anagram string combinations, I can't manage to find out a way.

For example : Input : "Wolf" Output : 1. wolf 2. wofl 3. wlof 4. wflo 5. wlfo 6. wfol 5. owlf 6. olfw . . . And so on.

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82

1 Answers1

4

Check this one:

public class Test {
        public static void main(String[] args) {
           String input = "Wolf";
            permutation(input, "");
        }    
        private static void permutation(String input, String sofar) {
            if (input.equals("")) {
                System.out.printf("%s,", sofar);
            }
            for (int i = 0; i<input.length(); i++) {
                char c = input.charAt(i);
                if (input.indexOf(c, i + 1) != -1)
                continue;
                permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
            }
        }
}

Output:

Wolf,Wofl,Wlof,Wlfo,Wfol,Wflo,oWlf,oWfl,olWf,olfW,ofWl,oflW,lWof,lWfo,loWf,lofW,lfWo,lfoW,fWol,fWlo,foWl,folW,flWo,floW
Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82