Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Thursday, 5 November 2020

Why use delegate?

Delegate is one of the most wrongly interpreted word by developers in C#.  Delegate is widely used inside .net framework itself. Let’s go further and break that delegate wall that every interviewer asks.

My Experience with Delegates

In my all years of experience I have used delegate several times and noticed that after I am done with development who ever over takes that code from me is not able to grasp that particular delegate logic.

 

If used wisely it can save a lot of time and lines of code but if used in inappropriately it will confuse everyone in future.

Purpose

It helps achieving following

1.      Encapsulation / Abstraction

2.      Security

3.      Callback

4.      Re-usability

Most common definition of Delegate

“Delegate is a keyword in .net that is used as function pointer” or

“Delegate is used for callbacks only”

Well nothing is wrong in these definition but these definition does not tell you the whole picture itself, it’s more confusing

Characteristics

Delegate has few characteristic

1.      Type safe

2.      Takes method in assignment

Let’s start by an example –

First let’s create our Product model

We are going to use this model

using System;

 

namespace Models

{

    public class Products

    {

        public string ProductName { get; set; }

        public int ProductId { get; set; }

    }

}

 

Let’s create and interface

General practice to create interface

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace BusinessLayer

{

    public interface ICustomer<T>

    {

        void Process(T products);

    }

}

 

Second inherit this interface in class

using Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace BusinessLayer

{

    public class FrequentCustomer : ICustomer<Products>

    {

        public void Process(Products product)

        {

            Console.WriteLine($"Product Count : 1");

            Console.WriteLine("--Product Details--");

            Console.WriteLine($"Name : {product.ProductName} Product Id : {product.ProductId}");

        }

    }

}

 

Process is the method which will be called by an anonymous later

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ServiceCallManager

{

    public static class ServiceCaller

    {

        public static void Invoke<TService>(Action<TService> action)

        {

            Type typ = typeof(TService);

            TService instance = (TService)Activator.CreateInstance(typ);

           

            action(instance);

        }

    }

}

 

Invoke is the method which takes Action<TService> type argument, in .Net Action is delegate whose return type is void

 



See the summary, it says “encapsulates

 

Now we all know delegate takes method in assignment (Encapsulates method)

Method can be in any form let’s say anonymous methods,

What is the anonymous method

“A method without name!”

 

Now let’s look into our next class

 

using BusinessLayer;

using Models;

using ServiceCallManager;

using System;

using System.Collections.Generic;

using System.Dynamic;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

namespace CallbackExample

{

    class Program

    {

        static void Main(string[] args)

        {

            IList<Products> products = new List<Products>();

 

            Products product1 = new Products();

            product1.ProductName = "Rice";

            product1.ProductId = 1;

            products.Add(product1);

 

            product1 = new Products();

            product1.ProductName = "Dal";

            product1.ProductId = 2;

            products.Add(product1);

 

            product1 = new Products();

            product1.ProductName = "Chana";

            product1.ProductId = 3;

            products.Add(product1);

 

 

            ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

 

            Console.WriteLine();

            Console.ReadKey();

        }

    }

}

ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

Remember that invoke method accepts delegate as argument and delegate encapsulates methods, so here inside Invoke method I am passing an anonymous method which will get invoked when action() is called which executes the anonymous method and calls the Process method of FrequentCustomer class

Let’s go step by step-

1.      Breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1));

2.      It goes inside Invoke method of static ServiceCaller class

3.      Via reflection we are creating object of ServiceT type (You can ignore this if you don’t understand reflection)

4.      At the last line of method action is called with parameter instance i.e. object of ServiceT type

5.      After action(instance) is called breakpoint comes to ServiceCaller.Invoke<FrequentCustomer>(x => x.Process(product1)); and it starts executing the x => x.Process(product1) part only

6.      You will notice that x is of type FrequentCustomer 



7.      So this part of execution calls the Process method or FrequentCustomer and also passing local parameter in it

Now the benefit of delegate here is I am able to local variable inside method i.e. product1 which may not be available in other class due to security reasons

Delegate helps me implement Encapsulatiopn, Security, Callback (Obviously), Re-usability and if used wisely Polymorphism also

 

For more blogs like this please visit http://codeinout.blogspot.com/ of follow me on https://twitter.com/ishooagarwal

Thanks

 

 

Saturday, 1 February 2020

How to find palindrome in a given string (Effective way)



Finding longest palindrome in a substring of a given string

Most famous and tricky question asked in a interview are related to palindrome
  1.  Check whether the given string is palindrome? 
  2.  Find the longest palindrome in a substring of a given string?
  3.  Find all possible palindrome in given string?

These are the common question asked around palindrome.
Everybody knows answers to these questions. Every developer can code the above problem statements.
Its not like interviewer is expecting that you cannot write code for these problems. He expects to see a solution which is fast and robust. That’s where you get an edge.
There are several ways to do this and all are correct. I am showing one of them which I think is more performance oriented and robust.
So, let’s proceed with logic
Consider a string ‘ssssbbssbbss’ as you can see easily that longest palindrome substring is ‘ssbbssbbss’
Now let’s create a logic
Step 1:
Convert it to charArray()

Now create a table



if I compare character at location 0 with 0 it will give me true
similarly, for 1,1 | 2,2 | 3,3, | and so on
let’s fill the table



Step 2:
Now start comparing characters with 0 to 1, 1 to 2, 2 to 3 and so on and fill the table



Now our basic record is generated. This will come handy later
Step 3:
Now will start comparing characters that are at least 2 indices apart and so one until first and last character and we keep filling this table until the very last column and reuse the same data
If we start comparing character at index 0 with character at index 2
Int i = 0; Int j = 2;
i.e. if arr[i] == arr[j]
after this add 1 in i and subtract 1 from j
and before we start comparing remember we already have data for this
Yes, i has value 1 and j has value 1 which is a palindrome and we already know that.
So we iterating through the step 3 and we’ll find our result.
Now after going through there 3 steps we can say that there is a rule
Rule
              For a string to be considered as palindrome, all it’s substring should be palindrome as well.
Now how’d you implement this in code.
Here it is –
public class Palindrome
{
       private string value;
       private int Length = 0;
       int[,] table = null;
       char[] s = null;
       public int stringLength = 0;
       public int minCount = 0;
       public Palindrome(string palindromeString)
       {
              value = palindromeString;
              Length = value.Length;
              table = new int[Length, Length];
              s = value.ToCharArray();
              Initialize();
       }

       private void Initialize()
       {
              for (int i = 0; i < Length; i++)
              {
                     table[i, i] = 1; 
                     if (i != Length - 1)
                     {
                            if (s[i] == s[i + 1])
                            {
                                   table[i, i + 1] = 1;
                            }
                            else {
                                 table[i, i + 1] = -1;
                            }
                      }
              }
       }

       public string FindLongestPalindromInString()
       {
              for (int i = 0; i < Length; i++)
              {
                    for (int j = i+2; j < Length; j++)
                    {
                          table[i, j] = FindAllPalindrome (i, j);
                          if (table[i, j] == 1 && j-i > stringLength)
                          {
                                 stringLength = j-i;
                                 minCount = i;
                          }
                    }
               }
               return value.Substring(minCount, (stringLength)+1);

       }

       private int FindAllPalindrome(int p, int q)
       {
             int result = 0;
             if (table[p, q] == 1)
            {
                  result = 1;
            }
             else if (table[p, q] == -1)
             {
                    result = -1;
             }
             else
             {
                    if (s[p] == s[q])
                    {
                          result = FindAllPalindrome(p + 1, q - 1);
                    }
                    else { result = -1; }
             }
             return result;
       }
}

Here's the result



I hope you find it helpful.
I know there are lot of things which I can do to make this code better.
Happy reading (ta-ta).

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...