Wednesday, March 10, 2021

Permutation Algorithm for Words C#

Introduction

A permutation, also called an “arrangement number” or “order, ” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB

Sample Code

 String input = "A B C D";
 List<string> str = input.Split(' ').ToList();
PermutationAlgorithm obj = new PermutationAlgorithm();
var lstPermute = obj.Permute(str);

Algorithm

using System.Collections.Generic;
using System.Text;
using System.Linq;
public class PermutationAlgorithm
{
 

    public  List<Permutation> Permute(List<string> str)
    {
        int n = str.Count;
        StringBuilder sb = permute(str, 0, n-1, new System.Text.StringBuilder());

        var lst = sb.ToString().TrimEnd('~').Split('~').ToList();     
        return lst.Select((x , index )=> new Permutation { KeyWords = x,Index = index+1 }).ToList();
    }


    /**
      * permutation function
      * @param str string to
      calculate permutation for
      * @param l starting index
      * @param r end index
      */
    private StringBuilder permute(List<string> str,
                                int l, int r, StringBuilder output)
    {
        if (l == r)
        {
            output.Append(string.Join(" ", str) + "~");
        }
        else
        {
            for (int i = l; i <= r; i++)
            {
                str = swap(str, l, i);
                permute(str, l + 1, r, output);
                str = swap(str, l, i);
            }
        }
        return output;
    }

    /**
    * Swap Characters at position
    * @param a string value
    * @param i position 1
    * @param j position 2
    * @return swapped string
    */
    public List<string> swap(List<string> a,
                            int i, int j)
    {
        string temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        return a;
    }

}
public class Permutation
{
    public int Index { get; set; }
    public string KeyWords { get; set; }
}

No comments: