Pages

Monday, November 8, 2021

Java 8 - Generate All Permutations of String

1. Overview

In this tutorial, We'll learn how to get and print all permutations of string in java. This can be solved in iterative and recursive approaches.

Iterative approach is much complex and recursive approach is simple to code.


Let us explore the examples in before java and with java 8 parallel streams.

For example input is ABC and output permutations are ABC, ACB, BCA, BAC, CAB, CBA.

Java 8 - Generate All Permutations of String


2. Java Generate All Permutations of String - Recursive


Understand the logic from the below diagram.

Java Generate All Permutations of String - Recursive

The initial state contains the initial string and each successive state can be computed by the following formula. each letter of the string will become the first letter of the string (swap positions) and then permute all of the remaining letters using a recursive call. 

package com.javaprogramto.programs.strings.permutations;

public class StringPermutationsExample1 {

	public static void main(String[] args) {

		stringPermuteAndPrint("", "ABC");
	}

	private static void stringPermuteAndPrint(String prefix, String str) {
		int n = str.length();
		if (n == 0) {
			System.out.print(prefix + " ");
		} else {
			for (int i = 0; i < n; i++) {
				stringPermuteAndPrint(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i));
			}
		}
	}

}


Output:
ABC ACB BCA BAC CAB CBA 
At the beginning of the method, prefix is empty. For each iteration, prefix will be added with the next character from input string. And the remaining the characters of the string are passed to the recursive call. This chain is invoked till the last character of the string.

Here, all possible combinations are printed on the console. Instead of this, we can store all of these values into a Set or List. List is better than Set because Set removes the duplicates.

For example, input TEST output will have the duplicates. So to hold the duplicates which are valid ones, we need to use the List instance.


3. Java 8 Generate All Permutations of String - Recursive


Next, let us use the java 8 streams and parallel executions for the larger inputs values.

Here, we use IntStream.range(0, n) method to run the for loop through from 0 to string length such as n.
Parallel() method to run the calls parallel for next character of string.
package com.javaprogramto.programs.strings.permutations;

import java.util.stream.IntStream;

public class StringPermutationsExample2 {

	public static void main(String[] args) {

		stringPermuteAndPrint("", "ABC");

	}

	// java 8 stream example
	private static void stringPermuteAndPrint(String prefix, String str) {
		int n = str.length();
		if (n == 0) {
			System.out.print(prefix + " ");
		} else {
			IntStream.range(0, n).parallel().forEach(
					i -> stringPermuteAndPrint(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
		}
	}

}

This program also produces the same output as before java 8 example.


4. Conclusion


In this article, We've seen how to get all permutations of string in java and java 8 streams.



No comments:

Post a Comment

Please do not add any spam links in the comments section.