Array-promo

Question

Find all the permutation of a word.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class permuteWord 
{  
    /*Function for swapping the characters at position I with character at position j  */
    public static String swapcharacter(String a, int i, int j) 
    {  
        char[] b =a.toCharArray();  
        char ch;  
        ch = b[i];  
        b[i] = b[j];  
        b[j] = ch;  
        return String.valueOf(b);  
    }  
      
    public static void main(String[] args)  
    {  
        String wd="";
        Scanner sc = new Scanner(System.in);    

        System.out.println("Enter a word");   
        
        wd =sc.next(); 
        int len = wd.length();  
        System.out.println("All the permutations of the string are: ");  
        makePermutation(wd, 0, len);  
    }  
      
    /*Function for making different permutations of the string  */
    public static void makePermutation(String str, int s, int e)  
    {  
        /*print string*/ 
        if (s == e-1)  
            System.out.println(str);  
        else  
        {  
            for (int i = s; i < e; i++)  
            {  
                /*Swapping the string by fixing a character  */
                str = swapcharacter(str,s,i);  
                /*Recursively calling function makePermutation() for rest of the characters*/   
                makePermutation(str,s+1,e);  
                /*Backtracking and swapping the characters again.  */
                str = swapcharacter(str,s,i);  
            }  
        }  
    }  
}  


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *