Thursday, June 13, 2019

Sample C# program to find the Permutation of a given string

The below C# program is used to print all the possible way to arrange the characters in the given string. Also known as Permutation.

Program :
  1. using System;
  1. public class Permutation
  2. {
  3. public void Permute(string inputString, int startIndex, int endIndex)
  4. {
  5. if (startIndex == endIndex)
  6. Console.WriteLine(inputString);
  7. else
  8. {
  9. for (int i = startIndex; i <= endIndex; i++)
  10. {
  11. inputString = Swap(inputString, startIndex, i);
  12. Permute(inputString, startIndex + 1, endIndex);
  13. inputString = Swap(inputString, startIndex, i);
  14. }
  15. }
  16. }
  17.  
  18. private string Swap(string a, int i, int j)
  19. {
  20. char temp;
  21. char[] arr = a.ToCharArray();
  22. temp = arr[i];
  23. arr[i] = arr[j];
  24. arr[j] = temp;
  25.  
  26. return new string(arr);
  27. }
  28. }

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. string inputString = "ABC";
  6. Permutation p = new Permutation();
  7. p.Permute(inputString, 0, inputString.Length - 1);
  8.  
  9. Console.ReadLine();
  10. }
  11. }
  12.  

Output :

ABC
ACB
BAC
BCA
CBA
CAB

No comments:

Post a Comment