Showing posts with label Note. Show all posts
Showing posts with label Note. Show all posts

Friday, September 6, 2019

Sample C# program to print left rotation of an array

Here is a sample C# program to print the left rotation of an array to k times very Quickly. This program succeeded all test cases in HackerRank challenge.

Program :
static public void Main ()
{
    int[] arr = {1, 4, 5, 6, 2};

    int length = arr.Length;
    int k = 2;

    LeftRotate(arr, length, k);
}
static void LeftRotate(int[] arr, int length, int k)
{
    for (int i = k; i < k + length; i++)
    {
        Console.Write(arr[i % length] + " ");
    }
}

Output :
5 6 2 1 4

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 :
using System;
public class Permutation
{
    public void Permute(string inputString, int startIndex, int endIndex)
    {
        if (startIndex == endIndex)
            Console.WriteLine(inputString);
        else
        {
            for (int i = startIndex; i <= endIndex; i++)
            {
                inputString = Swap(inputString, startIndex, i);
                Permute(inputString, startIndex + 1, endIndex);
                inputString = Swap(inputString, startIndex, i);
            }
        }
    }

    private string Swap(string a, int i, int j)
    {
        char temp;
        char[] arr = a.ToCharArray();
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;

        return new string(arr);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string inputString = "ABC";
        Permutation p = new Permutation();
        p.Permute(inputString, 0, inputString.Length - 1);

        Console.ReadLine();
    }
}


Output :

ABC
ACB
BAC
BCA
CBA
CAB