How to implement the java Program to generate permutation of string?

 What is permutation?

              It is a specific order of arrangement in alphabets or numbers. Generally, it arranges the set of elements.

In terms of mathematics, it uses factorial concept.

For eg:

 ‘XY’ – this is the input string.

The permutations are { ‘XY,’YX’}

Program implementation:

Class: permutationString

Member functions:

‘generateIt()’

‘main()’

Member variables:

‘str1’ ,’perm1’ , ‘s_remaining’, ‘sample’ -String variables

‘s’ – character variable

Logic:

  • Read the input.
  • Call the generateIt() function. it need to two arguments. One is the input string and permutation string.
  • ‘generateIt()’ function checks the input string is empty or not.
  • If it is not empty, it creates a for loop.
  • Create the permutations using recursion.
  • Finally, print the result.

Program:

public class permutationString {

    //User defined function to generate permutation

    public static void generateIt(String str1, String perm1) {

        if (str1.isEmpty()) {

            System.out.println(perm1);

            return;

        }

       //for loop to create permutaions

        for (int i = 0; i < str1.length(); i++) {

            char s = str1.charAt(i);

            String s_remaining = str1.substring(0, i) + str1.substring(i + 1);

            generateIt(s_remaining, perm1 + s);

        }

    }

    //main() function

    public static void main(String[] args) {

        String sample = "XYZ";

        System.out.println("Permutations of " + sample + ":");

        generateIt(sample, "");

    }

}

Output:

Compile and execute the program to get the output.

C:\raji\blog>javac permutationString.java

C:\raji\blog>java permutationString

Permutations of XYZ:

XYZ

XZY

YXZ

YZX

ZXY

ZYX

That’s all. The Java Program to generate the permutations using String is done. Keep Coding!!!

No comments:

Post a Comment