Permutation in Java Explained [With Coding Examples]

JAVA was developed by James Gosling at Sun Microsystems in the year 1995. Using JAVA, developers can create stable, secure, and resilient applications that are capable of running on almost any platform — including Linux, Windows, and macOS based operating systems.

The Write Once, Run Always property of JAVA (also known as WORA) also saves the need of recompiling code that has been compiled satisfactorily once already. This versatility of JAVA makes it an ideal language to integrate in-built complex logical and mathematical functionality into almost all types of cross-platform applications. 

The advantages of using JAVA to develop web-apps, as opposed to any other alternative (or popular) web development environment, extend to three main pillars of sustained application benefits, namely:

  1. JAVA syntax is easy to learn and easy to adapt to, and suitable for coders at every level of pace and complexity. This makes JAVA a safe bet for development teams that are subject to frequent personnel changes. The time taken for a new resource to align themselves to the common development platform (JAVA), is one of the least in the industry.
  2. JAVA is a high-level, object oriented programming language, which makes it completely modular in approach, and gives developers the ability to create functionally reusable chunks of code, thereby reducing effort. A vast library of in-built functions also reduces dependencies on other tertiary plugins or compiler add-ons, scripts, etc – which in turn gives JAVA one of the least implementation times.
  3. JAVA blends the best of all worlds by being platform-independent as discussed above. A web application that is developed in JAVA can be easily moved from one operating system to another with zero loss in functionality, and that’s a priceless utility to possess in any development environment.

As one of the aspects that makes JAVA so lucrative as a development platform for the web, its minimal implementation dependencies and mathematically sound syntax can be generously exploited to perform almost any mathematical or logical instruction by simply invoking an in-built function, with minimum additional customisation.

One of the brightest examples of this flexibility in code, is the ability to perform permutation in JAVA — more specifically, to truly randomise and find all possible permutations of all the characters available in a particular string.

In this guided tutorial, we will learn how to attempt to perform this permutation in JAVA by storing the first character of the string in a “tracked” location of the string, and invoking the generatePermutation() function to randomize different variations with all the other characters in the string.

Read: Java Interview Questions & Answers

Permutation in Java — the Concept of the Backtracking Algorithm

To find a solution to this problem of permutation in JAVA, we must first familiarise ourselves with a concept that has become widely accepted within the web development community, as the backtracking algorithm.

The backtracking algorithm is a recursive process that depends on periodically fixing one character of a given string and combining it with all possible permutations of all the other characters, and repeating this process with characters in every position of the string individually, to arrive at the maximum (and all possible) number of variations for that string.

This algorithm of permutation in JAVA is easier to understand in the context of a given string with three characters. Let’s say these three characters in a given string are A, B, and C.

The first step to perform this permutation in JAVA is to begin by fixing one character (we will always start by fixing the character available in the first position), and then performing a swap with all the remaining characters, by combining them with the original (fixed) character.

For example, in the ABC string example, we will perform our first three string iterations by fixing the character A (which is the first character in the ABC string), and then perform the swaps by replacing A with A, B, and C respectively.

We then arrive at the following combinations: ABC, BAC, and CBA.

The next step is to similarly “fix” the character found in the next position of the string (in this case, the character found at the second position of the string, namely B) and swapping the remaining characters (including the character that was fixed in the previous iteration).

Eventually, we will keep repeating this step with each level of randomisation achieved, till we arrive at a complete set of all possible permutations:

ABC

ACB

BAC

BCA

CBA

CAB

In the sample code/desired output section available at the end of this article, we will turn this attempt to perform permutation in JAVA, into legible code and thereby see the permutations being calculated in real time.

Performing a Permutation in JAVA — the Recursive Algorithm to Backtrack and Swap

A succinct summary of the process to take a random string and perform a thorough permutation in JAVA, can be described with the following step by step recursive algorithm:

  1. String Definition – First, define a string. You can always choose to accept a random string as an input variable, but for clarity of purpose and effort, we will use the predefined string ABC in this example.
  2. Character Fixing – Fix one character (start with the character in the first position and continue to swap it out against all the remaining characters).
  3. generatePermutation() – Invoke and use the output from the generatePermutation() function, for all the remaining characters.
  4. Recursive Backtracking – Perform the “backtracking” algorithm, and keep recursively swapping characters till your code reaches the end of the string (In our current example, till C).

Performing a Permutation in JAVA — Sample Code:

public class PermuteString {  

    //defining a function to swap the characters at position i with all the characters at position j  

    public static String swapString(String a, int i, int j) {  

// character definitions  for fixed characters in string

      char[] b =a.toCharArray();  

        char ch;  

// performing the swap in the next step

        ch = b[i];  

        b[i] = b[j];  

        b[j] = ch;  

        return String.valueOf(b);  

    }    

    public static void main(String[] args)  

    {  

//defining the default string ABC

        String str = “ABC”;  

//counting the string length

        int len = str.length();  

//printing all randomizations

        System.out.println(“The following are all the possible permutations of the string ABC: “);  

        generatePermutation(str, 0, len);  

    }  

          //defining a function to generate all possible permutations of the string

    public static void generatePermutation(String str, int start, int end)  

    {  

        // printing all the permutations  

        if (start == end-1)  

            System.out.println(str);  

        else  

        {  

            for (int i = start; i < end; i++)  

            {  

                //fixing a character to swap the string  

                str = swapString(str,start,i);  

                //calling the generatePermutation()function recursively for all remaining characters                generatePermutation(str,start+1,end);  

                //performing backtracking algorithm to swap characters all over again  

                str = swapString(str,start,i);  

            }  

        }  

    }  

}  

Performing a Permutation in JAVA — Output Derived from the Sample Code:

When you compile and run this sample could, the desired output should look somewhat like this:

The following are all the possible permutations of the string ABC:

ABC

ACB

BAC

BCA

CBA

CAB

Must Read: Interesting Java Projects & Topics

Conclusion

We hope you found this tutorial to perform a permutation in JAVA useful.  

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Learn More

Leave a comment

Your email address will not be published.

×