Thursday, May 29, 2014

For a given String, generate all possible permutations (All Possible Anagrams) of that String In Java



import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author Sachidananda
 */
public class StringPremutator {

public static void main(String[] args) {
System.out.println("Enter the strings to get all the combinations : ");
Scanner scanner = new Scanner(System.in);
String inputString = scanner.nextLine();
System.out.println("The Input you have provided is : "+inputString);
ArrayList<String> finalResult=permutate(inputString);
//int counter=0; // Had taken the counter to check if the permutation for a given length mathematically is correct.
System.out.println("The Results are as follows : ");
for(String results:finalResult){
System.out.println(results);
//counter++;
//System.out.println(counter);
}

}
/**
* List permutation of a string
* @param   String as in input.
* @return  ArrayList that has all the permutation of the input passed.
*/
public static ArrayList<String> permutate(String ins){
ArrayList<String> permutattionResult = new ArrayList<String>();
if(ins.length()==1){
permutattionResult.add(ins);
}else if(ins.length()>1){
int lastIdx=ins.length()-1;
String last=ins.substring(lastIdx);
String lastButRest=ins.substring(0,lastIdx);
permutattionResult=getPremutatorCombinations(permutate(lastButRest),last);
}
return permutattionResult;
}

/**
* @param ArrayList is passed which has all the characters in the string except the last
* @param Strig as last which is basically the character at the last index if the input string.
* @return ArrayList as result.
*/
private static ArrayList<String> getPremutatorCombinations(ArrayList<String> permutate, String last) {
ArrayList<String> result = new ArrayList<String>();
for(String data:permutate){
for(int i=0; i <=data.length();i++){
String permutedData=new StringBuilder(data).insert(i,last ).toString();
result.add(permutedData);
}
}
return result;
}


}


OUTPUT
===============

Enter the strings to get all the combinations : 
ABC
The Input you have provided is : ABC
The Results are as follows : 
CBA
BCA
BAC
CAB
ACB
ABC


No comments:

Post a Comment