Friday, 12 February 2016

Logic


1. How many times each character is repeating in a given string


            string str = "My Name is Bill"; 

            //Since String is the array of characters

            foreach (char x in str.Distinct())
            {
                int counter = 0; 

                if (!char.IsWhiteSpace(x))
                {

                    foreach (char y in str)
                    {
                        if (x == y)
                        {
                            counter = counter + 1;
                        }
                    }
                    Console.Write(string.Format("{0} is repeated {1} times", x, counter));
                }

            }

Using LINQ

      string str = "My Name is Bill";

      var x = from u in str.ToLower()
      where char.IsWhiteSpace(u) == false
      group u by u into g
      select new { Item = g.Key, count = g.Count() };

      foreach (var y in x)
      {
         
          Console.WriteLine("{0} is repeated {1} times", y.Item, y.count);
      }



2. List of N Prime Numbers

            bool isPrime = true;
            for (int i = 2; i <= 100; i++)
            {
                for (int j = 2; j <= 100; j++)
                {
                    if (i != j && i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    Response.Write(i + "is Prime" + "</br>");
                }

             }