Print all permutations of a string in c#

Csharp program for Print all permutations of a string. Here problem description and explanation.

// Include namespace system
using System;
// Csharp 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
			var first = text[a];
			// Get second character
			var second = text[b];
			// Put character
			text = text.Substring(0, b - 0) + first + 
              text.Substring(b + 1);
			text = text.Substring(0, a - 0) + 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)
		{
			Console.WriteLine(text);
			return;
		}
		for (var i = n; i < size; ++i)
		{
			// Swap the element
			text = this.swap(text, size, i, n);
			this.findPermutation(text, n + 1, size);
			// Swap the element
			text = this.swap(text, size, i, n);
		}
	}
	public static void Main(String[] args)
	{
		var task = new Permutation();
		var text = "ABC";
		var size = text.Length;
		task.findPermutation(text, 0, size);
		Console.WriteLine();
		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