Wednesday, 17 April 2019

Linq Query

#region RepeatableStringcount
            string input = "TRYARABT";
            var grouped = input.GroupBy(x => x).Where(c=>c.Count()>1).Select(group => new {
                                                                                                                  word =group.Key,
                                                                                                                  count = group.Count()
                                                                                                                                                    });
            var outputList= grouped.ToDictionary(x => x.word, x => x.count);
           
            foreach (var output in outputList)
            {
                Console.WriteLine(output.Key + " Count:- " + output.Value);
            }

 #endregion

#region Find 2nd highest salary

var secondHighestSalary= employess.GroupBy(sal=> new{sal.EmployeeName,sal.Salary})
.OrderByDescending(F=>F.Key.Salary)
.Skip(1).First().Select(emp=>new {EmployeeName=emp.Key.EmployeeName,Salary=emp.key.Salary})

#EndRegion

static void Main(string[] args)
 { 
 
 var inputs =new [] { "abcd", "dcba", "cabd", "xyz", "yxz", "uml" };

      var result = find(inputs.ToList());

 }

 public static List<List<string>> find(List<string> strList)

        {

            return strList.GroupBy(s => string.Concat(s.OrderBy(c => c))).Select(gr => gr.ToList()).ToList();

        }

Programming Puzzle


I've am trying to read a large text file and output the distinct words in it along with it's count. I've tried a couple of attempts so far, and this is by far the fastest solution I have come up with.
private static readonly char[] separators = { ' ' };

public IDictionary<string, int> Parse(string path)
{
    var wordCount = new Dictionary<string, int>();

    using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
    using (var streamReader = new StreamReader(fileStream))
    {
        string line;
        while ((line = streamReader.ReadLine()) != null)
        {
            var words = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                if (wordCount.ContainsKey(word))
                {
                    wordCount[word] = wordCount[word] + 1;
                }
                else
                {
                    wordCount.Add(word, 1);
                }
            }
        }
    }

    return wordCount;
}

  

string in with and without using reverse function in C#

/// REVERSE STRIG WITH USING C# FUNCTIONS
public class ReverseStrigs
    static void Main(string[] a)
    {
    Console.WriteLine("Enter string for Reverse");
        string str = Console.ReadLine();

        Console.WriteLine(Reverse(str));
        Console.ReadLine();
    }

    public static string Reverse(string str)
    {
        return new string(str.Reverse().ToArray());
    }
}
/// REVERSE STRIG WITHOUT USING C# FUNCTIONS          

 

public class ReverseStrigs
    static void Main(string[] ax)
    {
    Console.WriteLine("Enter string for Reverse");
        string str = Console.ReadLine();

        Console.WriteLine(Reverse(str));
        Console.ReadLine();
    }

    public static string Reverse(string str)
    {
        int strLength = str.Length;
        char[] array = new char[strLength];

        for (int i = 0; i < strLength; i++)
        {
            array[i] = str[strLength - 1 - i];
        }
        return new string(array);
    }
}

 

 Question 2: Swap neighbor char in string, For Example string “TAPAN” would be:


neighbor char in string

Answer:
  1. public static string SwapNeighbourChar(string strToSwap)  
  2. {  
  3.     char[] arraStr = strToSwap.ToCharArray();  
  4.     StringBuilder strbuild = new StringBuilder();  
  5.     for (int i = 0; i <= arraStr.Length - 1; i++)  
  6.     {  
  7.         if (i != arraStr.Length - 1)  
  8.         {  
  9.             strbuild.Append(arraStr[i + 1]);  
  10.         }  
  11.         strbuild.Append(arraStr[i]);  
  12.         i = i + 1;  
  13.     }  
  14.     return strbuild.ToString();  
  15. }  
Calling above method 
  1. static void Main(string[] args)  
  2. {  
  3.      Console.WriteLine(clsSwapNeighbour.SwapNeighbourChar("TAPAN"));  
  4.      Console.ReadLine();  
  5. }  

Prime number program using ASP.Net C#

A prime number can be divided only by itself or by 1 that number is called prime number.
Noted point:  The number 0 and 1 are not considered prime numbers.

Prime Numbers : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61..
                                                                                                                                             
Answer:
  1. public static bool IsPrimeNumbers(int number)  
  2. {  
  3.     bool returnMsg = false;  
  4.     for (int i = 2; i <= number; i++)  
  5.     {  
  6.         if ((number % i) == 0 && number != i)  
  7.         {  
  8.             returnMsg = false;  
  9.             return returnMsg;  
  10.         }  
  11.         else if (number == i)  
  12.         {  
  13.             returnMsg = true;  
  14.             return returnMsg;  
  15.         }  
  16.     }  
  17.     return returnMsg;  
  18. }  
Calling above method,
  1. static void Main(string[] args)  
  2. {  
  3.     string message = clsIsPrimeNumber.IsPrimeNumbers(17) == true ? "Prime Number" : "Not a prime number";  
  4.     Console.WriteLine(message);  
  5.     message = clsIsPrimeNumber.IsPrimeNumbers(4) == true ? "Prime Number" : "Not a prime number";  
  6.     Console.WriteLine(message);  
  7.     message = clsIsPrimeNumber.IsPrimeNumbers(11) == true ? "Prime Number" : "Not a prime number";  
  8.     Console.WriteLine(message);  
  9.     message = clsIsPrimeNumber.IsPrimeNumbers(21) == true ? "Prime Number" : "Not a prime number";  
  10.     Console.WriteLine(message);  
  11.     Console.ReadLine();  5




Factorial Number using Recursion in ASP.Net C#
Hello everyone, I am going to share the code sample for factorial number by using recursion. The factorial number formula. i.e.
L(n) = n*(n-1)
The example in detail as given below.
 public class factorial_Number
  {
        /// <summary>
        /// FACTORIAL OF A NUMBER USING RECURSION.
        /// </summary>
        public static int FactorialNumber(int number)
        {
            if (number == 0)
            {
                return 1;
            }
            return number * (FactorialNumber(number - 1));
        }

        static void Main(string[] ax)
        {
          int number = Convert.ToInt16(Console.ReadLine());

          //CALL FACTORIAL FUNCTION.
          Console.WriteLine(FactorialNumber(number));
          Console.ReadLine();  }  }



Find the most occurrence of a character in string C#?

public class CountMostOccurrenceCharacters
{
static void Main(string[] ss)
{
    Dictionary<charint> dicList = new Dictionary<charint>();
    int last = 0;


    Console.WriteLine("Enter the charactor string");

    foreach (char chr in Console.ReadLine())
    {
        int count;
        dicList.TryGetValue(chr , out count);


        count++;
        if (count > last)
        {
            last = count;
        }
        dicList[chr ] = count;
    }

    foreach (KeyValuePair<charint> charList in dicList)
    {
        if (charList.Value == last)
        {
            Console.WriteLine("{0}: {1}", charList.Key, charList.Value);
        }
    }
    Console.ReadLine();
}
}
  

fibonacci series using for loop in c# program

  1. public static void PrintFibonacciSeries(int limit)  
  2. {  
  3.     int digit1, digit2, digit3;  
  4.     digit1 = 0;  
  5.     digit2 = 1;  
  6.     digit3 = digit1 + digit2;  
  7.     Console.WriteLine(digit1);  
  8.     Console.WriteLine(digit2);  
  9.     Console.WriteLine(digit3);  
  10.     for (int i = 0; i < limit; i++)  
  11.     {  
  12.         digit1 = digit2;  
  13.         digit2 = digit3;  
  14.         digit3 = digit1 + digit2;  
  15.         Console.WriteLine(digit3);  
  16.     }  
  17. }  
Calling above method,
  1. static void Main(string[] args)  
  2. {  
  3.   clsFibonacci.PrintFibonacciSeries(10);  
  4.   Console.ReadLine();  
  5. }  

 



 A simple program that find which of the names in the `names` array occurs the maximum number of times


using System;
using System.Collections.Generic;

namespace Patterns
{
    public class FrequentItemFinder
    {
        /**
         * A simple class to hold one data item and the count of
         * how many times it has occurred
         */
        public class ItemCount
        {
            private String item;
            private int count;
            public ItemCount(String item, int count)
            {
                this.item = item;
                this.count = count;
            }
            public ItemCount(String item)
            {
                this.item = item;
                this.count = 0;
            }
            public String getItem() { return item; }
            public int getCount() { return count; }
            public void increment() { count += 1; }
        }

        /**
         * Take an array of items and return an array of unique items 
         * with counts
         */
        public interface ItemCounter
        {
            /**
             * Analyze the list, figure out the number of times
             * each unique data item appears in the list, and return
             * a list of ItemCount objects corresponding to each
             * unique data item and the number of times it occurs
             * in the list
             */
            List<ItemCount> analyze(List<String> list);
        }

        public class DictionaryBasedItemCounter : ItemCounter
        {
            public List<ItemCount> analyze(List<string> list)
            {
                var wordCount = new Dictionary<string, int>();
                foreach (var word in list)
                {
                    if (wordCount.ContainsKey(word))
                    {
                        wordCount[word] = wordCount[word] + 1;
                    }
                    else
                    {
                        wordCount.Add(word, 1);
                    }
                }

                List<ItemCount> itemCounts = new List<ItemCount>();
                foreach (var word in wordCount)
                {
                    itemCounts.Add(new ItemCount(word.Key, word.Value));

                }

                return itemCounts;
            }
        }

        /**
         * An implementation of ItemCounter interface which
         * sorts the input list using Collections.sort and then
         * counts the number of occurrences of each item by
         * making one pass through the sorted list
         */
        public class SortBasedItemCounter : ItemCounter
        {
            public SortBasedItemCounter() { }
            public List<ItemCount> analyze(List<String> list)
            {
                list.Sort();
                List<ItemCount> icList = new List<ItemCount>();
                String prev = null;
                ItemCount counter = null;
                foreach (var s in list)
                {
                    if (s.Equals(prev))
                    {
                        // Same item. Just increment the count
                        counter.increment();
                    }
                    else
                    {
                        // Item changed. Add previous item count to icList
                        if (counter != null)
                            icList.Add(counter);
                        counter = new ItemCount(s, 1);
                        prev = s;
                    }
                }
                // The last item has not yet been added to the list
                if (counter != null)
                {
                    icList.Add(counter);
                }
                return icList;
            }
        }

        /**
         * A class that allows us to choose between different
         * implementations of the ItemCounter interface based on the name
         * All the different implementations must be registered with this
         * class before they can be used.
         */
        public class ItemCounterChooser
        {
            Dictionary<String, Type> registeredCounters =
                new Dictionary<String, Type>();
            public void register(String name, Type counterType)
            {
                registeredCounters.Add(name, counterType);
            }

            /**
             * Return an instance of the ItemCounter class that was
             * registered using `name`
             * Return null if `name` was not registered at all.
             */
            public ItemCounter getItemCounterInstance(String name)
            {
                Type icType = registeredCounters[name];
                if (icType == null)
                    return null;
                return (ItemCounter)Activator.CreateInstance(icType);
            }
        }

        private ItemCounterChooser itemCounterChooser;
        private ItemCounter itemCounter;

        public FrequentItemFinder()
        {
            itemCounterChooser = new ItemCounterChooser();
            itemCounter = null;
            itemCounterChooser.register("SortBased",
                                        typeof(SortBasedItemCounter));
            itemCounterChooser.register("DictionaryBased",
                                        typeof(DictionaryBasedItemCounter));
        }

        public void selectItemCounterChooser(String itemCounterName)
        {
            itemCounter = itemCounterChooser.getItemCounterInstance(
                                                     itemCounterName);
        }

        /**
         * Find which string appears the most number of times in list
         * Use the ItemCounter to get a list of name,count pairs
         * and then find which one appears the maximum number of times.
         * In case of a tie, pick any one randomly
         */
        public String findFrequentString(List<String> list)
        {
            if (itemCounter == null)
                if (list.Count > 50)
                    selectItemCounterChooser("DictionaryBased");
                else
                    selectItemCounterChooser("SortBased");
            int max = -1;
            String frequentItem = null;
            foreach (var icount in itemCounter.analyze(list))
            {
                if (icount.getCount() > max)
                {
                    max = icount.getCount();
                    frequentItem = icount.getItem();
                }
            }
            return frequentItem;
        }

        /**
         * A simple program that find which of the names in the `names`
         * array occurs the maximum number of times
         */
        public static void Main(String[] args)
        {
            FrequentItemFinder frequentItemFinder =
                new FrequentItemFinder();
            List<String> names = new List<String>{
                          "Navin Kabra",
                          "Amit Paranjape",
                          "Navin Kabra",
                          "Amit Paranjape1",
                          "Navin Kotkar",
                          "Gaurav Kotkar"};
            String f = frequentItemFinder.findFrequentString(names);
            Console.WriteLine("The most frequent name is: " + f);
        }
    }
}

How to know the API version is not Latest

in input.text file
Mail App, Authentication API, v6
Video Call App, Authentication API, v7
Mail App, Data Storage API, v10
Chat App, Data Storage API, v11
Mail App, Search API, v6
Chat App, Authentication API, v8
Chat App, Presence API, v2
Video Call App, Data Storage API, v11
Video Call App, Video Compression API, v3

 public void CheckOldVersionApp(string path = @"c:\Input.txt")
        {
            string line;

            // Read the file and display it line by line.  
            List<string> lineStrings = new List<string>();

            using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
            using (var streamReader = new StreamReader(fileStream))
            {
                while ((line = streamReader.ReadLine()) != null)
                {
                    lineStrings.Add(line);
                }
            }

            Dictionary<string, int> apiVersionNumbers = new Dictionary<string, int>();

            foreach (var lineString in lineStrings)
            {
                string[] words = lineString.Split(',');
                if (!apiVersionNumbers.ContainsKey(words[1]))
                {
                    apiVersionNumbers.Add(words[1], Convert.ToInt32(words[2].Substring(2)));
                }
                else
                {
                    int versionNumber = apiVersionNumbers[words[1]];
                    if (versionNumber <= Convert.ToInt32(words[2].Substring(2)))
                    {
                        apiVersionNumbers[words[1]] = Convert.ToInt32(words[2].Substring(2));
                    }
                }
            }

            List<string> appNames = new List<string>();
            foreach (var lineString in lineStrings)
            {
                string[] words = lineString.Split(',');

                int versionNumber = apiVersionNumbers[words[1]];
                if (versionNumber > Convert.ToInt32(words[2].Substring(2)))
                {
                    if (!appNames.Contains(words[0]))
                        appNames.Add(words[0]);
                }
            }

            foreach (var appName in appNames)
            {
                Console.WriteLine(appName);
            }
        }
-----------------------------------------------------------------------------------------------------------------------------

Group Anagrams

 static void Main(string[] args)

        { 
  
var inputs =new [] { "abcd", "dcba", "cabd", "xyz", "yxz", "uml" };

      var result = find(inputs.ToList());

}

 public static List<List<string>> find(List<string> strList)

        {

            return strList.GroupBy(s => string.Concat(s.OrderBy(c => c))).Select(gr => gr.ToList()).ToList();

        }