Thursday, 3 October 2019

Implementing generic Linked List with O(n) time complexity for Addition


Implementing generic linked list and performing basic operation on them with O(1) time complexity is easier than what the developers think. It's just the hype of Data Structures and the word Time Complexity.


Linked list is basically a object which holds of another object of same type and so on for every other object until the reference to next object becomes null. What is this reference? It’s just a reference variable which has an object.


To understand this better let’s take an example.
How many of you have seen Naruto? Well specific for this answer I’m going to get little less views :-D

Do you understand the word Izanmi
In this every instance which Kabuto experience is an object which hold a reference to another instance and so on until null is reached
Getting it.

Now lets move to coding example-

using System;
using System.Collections.Generic;

namespace Stucts.ADT.GenericLinkedList
{
    public class Node<T>
    {
        public T data;
        public Node<T> next = null;
    }
}

It’s a simple class which have one variable to hold data and one to hold the reference of same type of object

using System;
using System.Collections.Generic;

namespace Stucts.ADT.GenericLinkedList
{
    public class SimpleGenericLinkedList<T>
    {
        Node<T> head = null;
        Node<T> tail = null;

        private Node<T> CreateNode(T data, Node<T> next)
        {
            Node<T> newItem = new Node<T>();
            newItem.data = data;
            newItem.next = next;
            return newItem;
        }


        public void Add(T data)
        {
            if (head == null)
            {
                head = CreateNode(data, null);
                tail = head;
            }
            else {
                tail.next = CreateNode(data,null);
                tail = tail.next;
            }
        }

        public void RemoveNode(T data)
        {
            if (head.data.Equals(data))
            {
                head = head.next;
            }
            else
            {
                head.next = Remove(data, head.next);
            }
        }

        public Node<T> Remove(T data, Node<T> current)
        {
            if (current != null)
            {
                if (current.data.Equals(data))
                {
                    current = current.next;
                }
                else
                {
                    current.next = Remove(data, current.next);
                }
            }
            return current;
        }

        public void ReadAll()
        {
            Node<T> current = head;
            while (current.next != null)
            {
                Console.WriteLine(current.data); ;
                current = current.next;
            }
            Console.WriteLine(current.data); ;
        }
    }
}

Here I have performed some vary basic operation like adding, removing from head and traversing the entire list
Now to insert every new node in linked list we need to traverse through all the nodes and then add the node in the last.
Due to this traversal adding new node in linked list becomes time consuming and less effective with Time Complexity of O(n). This is clearly an issue. We can solve this by performing one very basic step while adding every node
In your Generic Linked list class add Tail node just like Head and when you add new node make it tail and keep adding new elements to tail.

SimpleGenericLinkedList<int> lnkList = new SimpleGenericLinkedList<int>();
            lnkList.Add(1);
            lnkList.Add(2);
            lnkList.Add(3);
            lnkList.Add(4);
            lnkList.Add(5);
            lnkList.Add(6);
            lnkList.Add(7);
            lnkList.Add(8);
            lnkList.Add(9);
            lnkList.Add(10);
            lnkList.RemoveNode(6);
            lnkList.ReadAll();


This is how the linked list object looks like


Just look at the object lnkList for every new node it has next and that next has another next and goes on until the lnkList.next.next….next == null;



Well that’s how linked list works and with just an easy step you can perform addition in linked list cost effective i.e. O(1)

For more content like this follow and share the blog

Thanks.

Saturday, 28 September 2019

Performance comparison of Generic and non Generic List after JIT compilation


Performance of generic and non-generic list is well known. But there is a catch. We should always consider results which comes after JIT compilation. The difference between the test run of the code snippet and running the code after JIT does its job may surprise you.
  1. Now what happens when you run the test application for performance comparison.
  2. When you run the application, JIT runs i.e. Just in Time compiler.
  3. JIT compiles the application, optimize the code and finds the best approach to executes the code.
  4. All these JIT steps are time consuming which are included in first execution, so the execution time is always way more than actual run time
  5. So how you can calculate the actual run time? Simple, to check the performance of your test application with test data, call code snippet in a loop.

Example
private static void GenericListPerformance()
{
     var genList = new List<int>() { 10, 100, 13, 19, 14, 100, 99 };
     var nonGenList = new ArrayList() { 10, 100, 13, 19, 14, 100, 99 };

     var stWatch = Stopwatch.StartNew();
     genList.Sort();
     stWatch.Stop();
     Console.WriteLine("Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());

     stWatch = Stopwatch.StartNew();
     nonGenList.Sort();
     stWatch.Stop();
Console.WriteLine("Non Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());
}

Here I have created a simple method to compare the two list ArrayList and List<T>. I have used Stopwatch which is present in System.Diagnostics namespace of .net framework and then printed the messages with time.

static void Main(string[] args)
{
         for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(string.Format("<--------Call Number {0} -------->",i));
                GenericListPerformance();
                Console.WriteLine();
            }
}

Now this is where I have used the actual concept. I have called the same method in main inside a loop which runs 5 times. So, when it run for first time JIT can optimize the code and find the best approach to run this code. Later, JIT will use the native code and give us the best results.

Result

See the results.
For first run the execution time is-
For Generic - 0.0263
For Non-Generic – 0.233
And later it came to be line
Generic – 0.0012, 0.0013, 0.0011, 0.0013
Non-Generic – 0.0032, 0.0026, 0.0026, 0.0029



Therefor, we should always consider the JIT time

Subscribe to my blog if you want to get notified about more detailed analysis of topics. Comment if you have any question or want me to do some analysis on the topic you want.
Thanks

Friday, 20 September 2019

Default implementation of method in interface(New feature of interface)


The latest version of c# allows you to define body of interface method.



For example :-
Consider you have a project of Asset Management which has an interface IAsset and which has properties AssetName, AssetAge, Id and so on

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stucts.New_Features.Interface
{
    interface IAsset
    {
        string AssetName { get; set; }
        string AssetAge { get; set; }
        string Id { get; set; }

    }
}

Now consider you have this interface inherited in multiple classes like FixedAssets, TemporaryAssets and so on

using System;
using Stucts.New_Features.Interface;

namespace Stucts.New_Features
{
    class FixedAsset : IAsset
    {
        public string AssetName { get; set ; }
        public string AssetAge { get; set; }
        public string Id { get; set; }
    }
}

Consider you want to add new feature to you application which moves asset to archive after certain years as per customer needs. It may be possible that you need to implement this logic for all kind of asset or just for few or some different logic based on other calculation.
In older version you need to define a non body method in interface and implement that method in all the other classes and. In some cases this might not seem a very big issue but I know when you are working on an ultra large scale software then this is a headache no one wants.



In C# 8.0 you can define default implementation of a method in interface and classes can use that method or if you can give different definition to same method in child classes

        public void MoveAssetToArchive(int age)
        {
              //Your log here
        }

You can start using this method in all the child classes without implementing it

FixedAsset  _fixAsset = new FixedAsset () {
AssetAge="4",
       AssetName="HTC Explorer Mobile phone",
              Id = "1001"
       };
       IAsset _IAsset = _fixAsset;
       _IAsset.MoveAssetToArchive(4);

Notice the following section of the test:

IAsset _IAsset = _fixAsset;
       _IAsset.MoveAssetToArchive(4);


Well that saved lot of time and effort :)

Similarly you can also declare variable as well as static members in interface
I would love if you guys create a demo project with scenario where we might need to declare static members and behaviors in an interface. Please do try to create a Demo. I will create a demo and with a scenario and write it in the blog soon so that we can discuss it. Comment if you have any question or want to discuss something. Reach out to me at ishooagarwal@gmail.com. Please add [Blog] in subject so that I can differentiate regular mail.
Meanwhile follow and subscribe the blog to get notifications of the blog
Thanks.

Tuesday, 17 September 2019

Passing data form one component to another (Sibling component) in angular 8





This blog shows you how to pass data from one component to another using EventEmitter
First create a service that could be injected in both the component (ANGULAR CLI COMMANDng g s customer-forms’) this will create a service with the name customerForms.service.ts
Now create a method in service that will be called from component on click, Let’s call is PassData
PassData(DataSource)
    {
        console.log(DataSource);
    }

Create a EventEmitter object which will emit the data
$dataSource = new EventEmitter();

Use this $dataSource variable in PassData method
PassData(DataSource)
    {
        console.log(DataSource);
        this.$dataSource.emit(DataSource);
    }

Now let’s create a method on component which will call PassData of service
Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.customerRequestService.PassData(CustomerRequest);
  }

Call this method on click of any html component.
<section class="col-md-3 border cursor-action" (click)="Edit(customerRequest)" 
    *ngFor="let customerRequest of customerRequests">

After running This you will see logs in console


Now we need to handle this emit in other component
For this we need subscribe to the variable $dataSource of service in receiving component in ngInit()
this.customerRequestService.$dataSource
      .subscribe((data=> {console.log('DataSource received'data);
      this.Edit(data);
    });

And finally
  Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.form.setValue({
      CompanyName:CustomerRequest.CompanyName,
      Name: CustomerRequest.Name,
      SoftwareId:CustomerRequest.SoftwareId,
      RelationshipDuration:CustomerRequest.RelationshipDuration,
      RequestMessage:CustomerRequest.RequestMessage
    });
  }

After doing all this you can see that the code is working in the console of browser


Thanks
Do not forget to subcribe to my blog i.e. codeinout.blogspot.com

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 ...