Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » How To Permute String in Java

In this post , My objective is to show the permutation of String in different manner using recursion.

public static void main(String[] args) {  
        System.out.println(StringPermutation.getPermutation("abcd"));  
  
    }  

Now let us write the original code or the function that will go recursively...

public static List<String> getPermutation(String input)
{  
  
        List<String> collection = null;  
  
        if (input.length() == 1) {  
            collection = new ArrayList<String>();  
            collection.add(input);  
            return collection;  
        } else {  
            collection = getPermutation(input.substring(1));  
           
            Character first = input.charAt(0);  
           
            List<String> result = new ArrayList<String>();  
            for (String str : collection) {  
                for (int i = 0; i < str.length(); i++  ) {  
                    String item = str.substring(0, i) +  first  
                            +  str.substring(i);  
                    result.add(item);  
                }  
                String item = str.concat(first.toString());  
                result.add(item);  
            }  
            return result;  
        }  
  

The program goes like:
import java.util.ArrayList;  
import java.util.List;  
  
public class StringPermutation {  
  
    public static List<String> getPermutation(String input) {  
  
        List<String> collection = null;  
  
        if (input.length() == 1) {  
            collection = new ArrayList<String>();  
            collection.add(input);  
            return collection;  
        } else {  
            collection = getPermutation(input.substring(1));  
           
            Character first = input.charAt(0);  
           
            List<String> result = new ArrayList<String>();  
            for (String str : collection) {  
                for (int i = 0; i < str.length(); i++  ) {  
                    String item = str.substring(0, i)  +first  
                              +str.substring(i);  
                    result.add(item);  
                }  
                String item = str.concat(first.toString());  
                result.add(item);  
            }  
            return result;  
        }  
  
    }  

  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        System.out.println(StringPermutation.getPermutation("abcd"));  
  
    }  
}
We are done!!
The output will be..
[abcd, bacd, bcad, bcda, acbd, cabd, cbad, cbda, acdb, cadb, cdab, cdba, abdc, badc, bdac, bdca, adbc, dabc, dbac, dbca, adcb, dacb, dcab, dcba]

 

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply