Print all permutations of a string in java

Java program for Print all permutations of a string. Here more information.

// Java program for
// Print all permutations of a string
public class Permutation
{
	// Swapping two string elements by index
	public String swap(String text, int size, int a, int b)
	{
		// Check valid location of swap element
		if ((a >= 0 && a < size) && (b >= 0 && b < size))
		{
			// Get first character
			char first = text.charAt(a);
			// Get second character
			char second = text.charAt(b);
			// Put character
			text = text.substring(0, b) + 
              first + text.substring(b + 1);
			text = text.substring(0, a) + 
              second + text.substring(a + 1);
		}
		return text;
	}
	// Method which is print all permutations of given string
	public void findPermutation(String text, int n, int size)
	{
		if (n > size)
		{
			return;
		}
		if (n == size)
		{
			System.out.println(text);
			return;
		}
		for (int i = n; i < size; ++i)
		{
			// Swap the element
			text = swap(text, size, i, n);
			findPermutation(text, n + 1, size);
			// Swap the element
			text = swap(text, size, i, n);
		}
	}
	public static void main(String[] args)
	{
		Permutation task = new Permutation();
		String text = "ABC";
		int size = text.length();
		task.findPermutation(text, 0, size);
		System.out.println();
		text = "abcd";
		size = text.length();
		task.findPermutation(text, 0, size);
	}
}

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved