Monday, April 22, 2024

Reverse string acbd#FGHIJKLa-34!azdd-e33fass3-1 to ssaf#eddzaaLK-34!JIHG-F33dbca3-1

 Reverse a string with characters being intact. 


using System;

using System.Linq;


namespace RetrieveData

{

    internal class Program3

    {



        static void Main(string[] args)

        {


            var myString = "acbd#FGHIJKLa-34!azdd-e33fass3-1";


            Console.WriteLine(myString);


            char[] chars = myString.ToCharArray();


            string original = string.Empty;

            string toBeReversed = string.Empty;


            foreach (char c in chars)

            {

                if (Char.IsLetter(c))

                {

                    toBeReversed += c.ToString();

                    original += " ";

                }

                else

                {

                    original += c.ToString();

                }

            }


            var stringArray = toBeReversed.ToCharArray();


            var reverseArray = stringArray.Reverse().ToArray();


            var reversedString = new String(reverseArray);


            var newString = string.Empty;

            int k = 0;

            for (int i = 0; i < original.Length; i++)

            {

                if (original.Substring(i, 1) == " ")

                {


                    newString += reversedString.Substring(k, 1);

                    k++;

                }

                else

                {

                    newString += original.Substring(i, 1);

                }

            }


            Console.WriteLine(newString);

            Console.ReadLine();



        }



    }

}


Saturday, April 20, 2024

Add and remove values from in memory db

  internal class Program

 {


     static Dictionary<string, List<KeyValuePair<string, string>>> db = new Dictionary<string, List<KeyValuePair<string, string>>>();


     static void Main2(string[] args)

     {


         AddToDb("A", "B", "C");

         AddToDb("A", "D", "E");


         AddToDb("I", "J", "K");

         AddToDb("I", "L", "M");


         RemoveFromDb("A", "B");

         RemoveFromDb("I", "J");


         Console.WriteLine(db.Count);


     }


     private static bool RemoveFromDb(string key, string fieldKey)

     {


         if (!db.ContainsKey(key))

         {

             return false;

         }

         else

         {

             var items = db[key];


             foreach (var item in items)

             {

                 if (item.Key == fieldKey)

                 {

                     items.Remove(item);

                     return true;

                 }

             }

         }

         return false;



     }


     private static void AddToDb(string key, string fieldkey, string fieldValue)

     {


         if (db.ContainsKey(key))

         {

             var list = db[key];

             var kvp = new KeyValuePair<string, string>(fieldkey, fieldValue);

             list.Add(kvp);

         }

         else

         {

             var list = new List<KeyValuePair<string, string>>();

             var kvp = new KeyValuePair<string, string>(fieldkey, fieldValue);

             list.Add(kvp);

             db.Add(key, list);

         }

     }

 }

Check if the given strings are anagrams.

   private static bool isAnagram(string str1, string str2)

  {


      if (str1.Length != str2.Length) { 

       return false;

      }


      char[] string1Array = str1.ToCharArray();

      char[] string2Array = str2.ToCharArray();


      Array.Sort(string1Array);

      Array.Sort(string2Array);



      if (string1Array.SequenceEqual(string2Array))

      { return true; }


      return false;


  }

Distribute the chocolates among children

    private static List<int> DistributeEqually(List<int> bags ,  int children )

   {


       List<int> equally = new List<int>();


       int totalCount = 0; 


       foreach ( int bag in bags )

       {

           totalCount = totalCount + bag;

       }


       int equalCount = totalCount/children;


       int nonEqualCount = totalCount % children;


       for ( int i = 0;i < children; i++)

       {

           equally.Add(equalCount);

       }


       for (int j = 0; j < nonEqualCount; j++)

       {

           equally[j] = equally[j] + 1;

       }


       return equally;



   }

Find the sum of numbers in a string part 2

 using System;


namespace RetrieveData

{

    internal class Program2

    {



        static void Main(string[] args)

        {


            int addedValue = AddNumber("A1B3C5D6$623325");


            Console.WriteLine($"The sum of numbers in the given string  is {addedValue}");

            Console.ReadLine();

        }


        private static int AddNumber(string  v)

        {

            int num;

            int sum = 0;

            for (int i = 0; i < v.Length; i++)

            {


                 bool isNumber = int.TryParse(v.Substring(i,1), out  num);

                

                if (isNumber)

                {

                    sum += num;


                }

                                

            }

            return sum;

        }

    }

}


Find the sum of number in a given number.

   static void Main(string[] args)

  {


      int addedValue = AddNumber(23325);


      Console.WriteLine($"The sum of numbers in the given number is {addedValue}");

      Console.ReadLine();

  }


  private static int AddNumber(int v)

  {

      string num = v.ToString();


      int sum = 0;

      for (int i = 0; i < num.Length; i++)

      {

          sum += int.Parse(num.Substring(i, 1));

      }

      return sum;

  }

Wednesday, January 19, 2022

Exceptions filter

 public class CommonExceptionsFilter : ExceptionFilterAttribute

  {
      private readonly ILogger logger;
      public CommonExceptionsFilter(ILogger<CommonExceptionsFilter> logger)
      {
          this.logger = logger;
      }
 
      public override void OnException(ExceptionContext context)
      {
          context.HttpContext.Response.GetTypedHeaders().ContentType = null;
          bool isWarning = false;
 
          if (context.Exception is NotFoundException notFoundException)
          {
              isWarning = true;
              if(!string.IsNullOrWhiteSpace(notFoundException.Message))
              {
                  Dictionary<stringstring[]> output = new Dictionary<stringstring[]>();
                  output.Add("Message"new string[] { notFoundException.Message });
                  context.Result = new ObjectResult(output);
              }
              context.HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
          }
          else if (context.Exception is ArgumentException argumentException)
          {
              isWarning = true;
              Dictionary<stringstring[]> output = new Dictionary<stringstring[]>();
              // remove the last line from the message as it repeats the parameter name
              string paramName = string.IsNullOrWhiteSpace(argumentException.ParamName) ? null : argumentException.ParamName;
              string message = argumentException.Message.Contains(Environment.NewLine)
                  ? argumentException.Message.Substring(0, argumentException.Message.LastIndexOf(Environment.NewLine))
                  : argumentException.Message;
              output.Add(paramName ?? "Argument"new string[] { message });
              context.Result = new BadRequestObjectResult(output);
              context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
          }
          else
          {
              context.Result = new ObjectResult(new { Error = new string[] { context.Exception.Message } });
              context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
          }
 
          context.ExceptionHandled = true;
          if (isWarning)
          {
              logger.LogWarning(new EventId(context.HttpContext.Response.StatusCode), context.Exception, context.Exception.Message);
          }
          else
          {
              logger.LogError(new EventId(context.HttpContext.Response.StatusCode), context.Exception, context.Exception.Message);
          }
 
          base.OnException(context);
      }
  }