Search This Blog

Monday, August 9, 2021

Duplicate

Q1: Write a code to remove the duplicates from array of integer which as 1000 integers init. 
Q2: Given a list of strings, find all duplicates and their counts.

===================================================================================
Q1: Write a code to remove the duplicates from array of integer which as 1000 integers init. 

Answe:
static void Main(string[] args)
        {

           //Write a code to remove the duplicates from array of integer which as 1000 integers init. 

var arrayobj = new int[] { 1, 3, 5, 7, 9, 3, 5, 6, 3, 7, 9, 2, 5, 9, 4, 6, 8, 3, 2, 1, 9};
var removeduplicate = arrayobj.DistinctBy(x => x).ToArray();
           
        }

===================================================================================
Q2: Given a list of strings, find all duplicates and their counts.

Answer:


internal class Program
{
    static void Main(string[] args)
    {
        // Q: Given a list of strings, find all duplicates and their counts.
        var strlist = new List<string>() { "apple", "bat", "cat", "apple", "bat", "bat", "rat", "cat" };

        var objdictionary = strlist
            .GroupBy(x => x)
            .OrderBy(g=>g.Count())
            .ToDictionary(g => g.Key, g => g.Count());

        foreach (var item in objdictionary)
        {
            Console.WriteLine("Word, Count  is " + item.Key + ", " + item.Value);
        }


    }
}

Palindrome

 Q: Write a code to check whether a string is palindrome or not?
====================================================================================

public void PalindrometrickOne()
{
    //string word = "MADAMPO";
    string word = "MADAM";
    int wordlength = word.Length;

    // forloop and check i and length - i character are same or not

    for (int i = 0; i < wordlength / 2; i++)
    {
        if (word[i] != word[wordlength - 1 - i])
        {
            // if for once its not, exit the loop and give error .
            Console.WriteLine("Word is not palindrom");
            return; //it will be exit form the whole method. 
        }
    }

    // reach only if 'return' never get executed. 
    Console.WriteLine("The given word is palindrome");
}