•  
  • Archives for c# (83)

Stack with LinkedList Implementation

Categories: Data Structures
Comments: No Comments
Published on: December 12, 2011

Naive implementation of Stack in C# uses array. In this post, I have implemented the stack with LinkedList. This implementation is not thread safe.

using System;
using System.Collections;
using System.Collections.Generic;

namespace CodeCodeCode
{
    public class StackLinkedList : IEnumerable, ICollection
    {
        private readonly LinkedList _container;

        public StackLinkedList()
        {
            _container = new LinkedList();
        }

        public StackLinkedList(IEnumerable collection)
        {
            foreach (T element in collection)
            {
                _container.AddLast(element);
            }
        }

        public StackLinkedList(Stack _stack)
        {
            while (_stack.Count > 0)
            {
                T element = _stack.Pop();

                _container.AddLast(element);
            }
        }

        #region ICollection Members

        public void Add(T item)
        {
            throw new NotImplementedException();
        }

        public void Clear()
        {
            _container.Clear();
        }

        public bool Contains(T item)
        {
            return _container.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        int ICollection.Count
        {
            get { return _container.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(T item)
        {
            return _container.Remove(item);
        }

        #endregion

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            foreach (T element in _container)
            {
                yield return element;
                _container.Remove(element);
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        public T Pop()
        {
            LinkedListNode element = _container.First;

            _container.Remove(element);

            return element.Value;
        }

        public void Push(T element)
        {
            _container.AddFirst(element);
        }

        public T Peek()
        {
            return _container.First.Value;
        }

        public int Count()
        {
            return _container.Count;
        }
    }
}
    [TestClass]
    public class UnitTest1
    {

        private StackLinkedList _collection;

        public UnitTest1()
        {
            _collection = new StackLinkedList();
        }

        [TestMethod]
        public void PushMethod()
        {
             _collection.Push(1);
             _collection.Push(2);
             _collection.Push(3);
            Assert.AreEqual(3, _collection.Peek());
            Assert.AreEqual(3, _collection.Pop());
            Assert.AreEqual(2, _collection.Pop());
            Assert.AreEqual(1, _collection.Pop());
            Assert.AreEqual(0, _collection.Count());
        }

    }

Windows Server AppFabric

Categories: Programming, Scalability, Web
Tags: ,
Comments: 1 Comment
Published on: July 19, 2011

Caching and reliable hosting is one the important elements for high available and scalable applications. Microsoft delivers Microsoft server appfabric. Two major components are Caching and Hosting. OK, i dont much know about hosting except the fact that it uses Microsoft Activation service, and I think, IIS is using it internally. Again, I m not very familiar with it. But you can learn more in the following URL:
Microsoft AppFabric
and Microsoft provides a training kit which is really useful :
AppFabric Traning Kit

As far as caching, AppFabric Cache used to be velocity cache. It s more than a distributed key value pair, it has many other features such as tags, where you can tag the key value pairs and then you can get them by tag. Moreover, you can create regions to store the relative items within an organization. For example: You can have a student cache, teacher cache, classes cache, etc. You dont have to stick everything into a single cache.

Just like other cache services, the API provides, Add (Adds an item to Cache), Get(Gets an item from cache), Put(Adds or updates an item), Remove methods(Removes an item from cache). Moreover, you can handle concurrency with Optimistic or Pessimistic Concurrency. Usually, you would like to define these in an interface and wrap the Factory Method of Data Classes. In terms of configuration, there are several configuration parameters for appfabric cache, during development, I usually prefer storing the configuration in the dedicated config file, such as cache.config. Moreover, in your application you would prefer to wrap the datacachefactory class, instantiate it and keep it live as long as the application lives.

You can set expiration time for the items in the cache, default is 10 minutes. You can set it so that it doesn’t expire etc.

There is cache eviction, which occurs when the machine the cache is on, runs out of memory. The cache items becomes evicted and drops. Least recently used algorithm is used for this implementation.

While developing code with cache, it is always good to do defensive programming, because there might be several problems, such as items might expire, cache servers might go down etc. So it is very desirable to consider all these failures.

One important point is that, every item you store in the cache should be serializable. All the primitive type in C#.Net are serializable, if you are creating your own types, make sure you make them serializable, there are couple ways to do that, such as implementing ISerializable interface or by using DataContract and DataMember attributes (Which WCF uses). Once your items are serializable you can store them in the cache.

Usual usage of cache is to be placed in front of database. So each request doesnt go to database but instead, it gets the data from cache which increases the response time of the application. This is just one of the usage of cache. Cache basically takes the load of the database.

Binary Search Tree Implementation via C#

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: July 10, 2011

Below is my binary search tree implementation (Not self balancing). Binary search trees are very common data structure and being used by many algorithms. Furthermore, binary search trees can be adopted to solve many algorithms, problems and puzzles.

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

namespace FiratAtagun.DataStructures
{
    public abstract class Node :  IEquatable, IEquatable> where T : IComparable
    {
        public T Value { set; get; }

        protected Node(T value)
        {
            Value = value;
        }

        protected Node()
        {

        }

        public override string ToString()
        {
            return Value.ToString();
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public bool Equals(T other)
        {
            return Value.Equals(other);
        }

        public bool Equals(Node other)
        {
            return Value.Equals(other.Value);
        }

        public static bool operator <(Node left, Node right)
        {
            if(left.Value.CompareTo(right.Value) < 0)
            {
                return true;
            }

            return false;
        }

        public static bool operator >(Node left, Node right)
        {
            if (left.Value.CompareTo(right.Value) > 0)
            {
                return true;
            }

            return false;
        }

    }
}

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

namespace FiratAtagun.DataStructures
{
    public class TreeNode : Node where T : IComparable
    {

        public TreeNode LeftChild { set; get; }
        public TreeNode RightChild { set; get; }

        public TreeNode()
        {
        }

        public TreeNode(T value): base(value)
        {
        }
    }
}

using System;
using System.Collections.Generic;

namespace FiratAtagun.DataStructures
{
    public class BinaryTree : IEnumerable, IEnumerable> where T: IComparable
    {

        public TreeNode Root { set; get; }

        public BinaryTree()
        {

        }

        public BinaryTree(IEnumerable collection)
        {
            foreach (var item in collection)
            {
                Insert(item);
            }
        }

        public void Insert(T value)
        {
           Insert(new TreeNode(value));
        }

        public void Insert(TreeNode treeNode)
        {
            if (ReferenceEquals(Root, null))
            {
                Root = treeNode;
                return;
            }

            var currentNode = Root;

            var node = treeNode;

            while (true)
            {
                if (node < currentNode)
                {

                    if (ReferenceEquals(currentNode.LeftChild, null))
                    {
                        currentNode.LeftChild = node;
                        break;
                    }
                    currentNode = currentNode.LeftChild;
                    continue;
                }

                if (node > currentNode)
                {

                    if (ReferenceEquals(currentNode.RightChild, null))
                    {
                        currentNode.RightChild = node;
                        break;
                    }
                    currentNode = currentNode.RightChild;
                    continue;
                }
            }
        }

        public void InsertRecursively(T value)
        {
            var node = new TreeNode(value);

            if(ReferenceEquals(Root, null))
            {
                Root = node;
                return;
            }

            var currentNode = Root;

            InsertRecursively(currentNode, node);
        }

        public void InsertRecursively(TreeNode currentNode , TreeNode node)
        {
            if(node < currentNode)
            {
                if(ReferenceEquals(currentNode.LeftChild,null))
                {
                    currentNode.LeftChild = node;
                    return;
                }
                InsertRecursively(currentNode.LeftChild, node);
                return;
            } 

            if(node > currentNode)
            {
                if(ReferenceEquals(currentNode.RightChild, null))
                {
                    currentNode.RightChild = node;
                    return;
                }
                InsertRecursively(currentNode.RightChild, node);
                return;
            }
        }

        public int NumberOfNodes
        {
            get { return NumberOfNodesMethod(); }
        }

        private int NumberOfNodesMethod()
        {
            if(ReferenceEquals(Root,null))
            {
                return 0;
            }

            return NumberOfNodesImpl(Root);
        }

        private static int NumberOfNodesImpl(TreeNode treeNode)
        {
            if(ReferenceEquals(treeNode, null))
            {
                return 0;
            }

            var count = 1 + NumberOfNodesImpl(treeNode.LeftChild) + NumberOfNodesImpl(treeNode.RightChild);

            return count;
        }

        public int Height
        {
            get { return GetHeight() -1; }
        }

        private int GetHeight()
        {
            if(ReferenceEquals(Root, null))
            {
                return 0;
            }

            return GetHeight(Root);
        }

        private static int GetHeight(TreeNode node)
        {
            if(ReferenceEquals(node, null))
            {
                return 0;
            }

            return 1 + Math.Max(GetHeight(node.LeftChild), GetHeight(node.RightChild));
        }

        public void PreOrderTraversal()
        {
            if(ReferenceEquals(Root, null))
            {
                return;
            }

            var currentNode = Root;

            PreOrderTraversal(currentNode);
        }

        public void PreOrderTraversal(TreeNode node)
        {
            if(ReferenceEquals(node, null))
            {
                return;
            }

            Console.WriteLine(node.Value);
            PreOrderTraversal(node.LeftChild);
            PreOrderTraversal(node.RightChild);
        }

        public void InOrderTraversal()
        {
            if(ReferenceEquals(Root, null))
            {
                return;
            }

            InOrderTraversalImpl(Root);
        }

        public void InOrderTraversalImpl(TreeNode node)
        {
            if(ReferenceEquals(node, null))
            {
                return;
            }

            InOrderTraversalImpl(node.LeftChild);
            Console.WriteLine(node.Value);
            InOrderTraversalImpl(node.RightChild);
        }

        public void PostOrderTraversal()
        {
            if(ReferenceEquals(Root,null))
            {
                return;
            }

            PostOrderTraversalImpl(Root);
        }

        public void PostOrderTraversalImpl(TreeNode node)
        {
            if(ReferenceEquals(node, null))
            {
                return;
            }

            PostOrderTraversalImpl(node.LeftChild);
            PostOrderTraversalImpl(node.RightChild);
            Console.WriteLine(node.Value);
        }

        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        IEnumerator> IEnumerable>.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}

LinkedList Notes

Categories: Algorithms, Programming
Tags:
Comments: 2 Comments
Published on: July 7, 2011

LinkedList is a common data structure being used. One of the difference between linked list and array based structures are, linked list doesn’t require contiguous memory space. Moreover, expansion within array based data structures bases on a load factor that s determined by the engineers who build the structures, and expansion of arrays usually twice the size of the current size. During expansion of the array, CLR creates a new array with the new size and then copy all the entities from one array to another. Even though this seems to be a an easy operation, as you data grows, it might become slow. Imagine, your array size becomes 5 million elements, next expansion would require contiguous memory to hold 10 million blocks. So this operation becomes very expensive. Benefit of linked list in the aspect is that, it doesn’t require contiguous memory space, nodes can be anywhere withing the Virtual Memory. Since we keep pointers to the nodes, that is sufficient to access any node which is linked by another node. Therefore the issue we mentioned above doesn’t happen with linked list.

There can be several algorithms and problems based on linked list due to the fact that linked list is convenient for multiple pointer usages, recursion, iteration, reversing etc.
Some of the examples are follows and the best way to practice them is to write code for it after understanding them.

If there is a cycle in a given linked list, you can find it by marking the visited nodes as visited, if you see a visited node again, you halt. This solution requires you to modify the Node structure and add a bolean to it. Another solution would be to have two pointers at the beginning, one that moves one by one node, and another pointer, that moves 2 nodes at a time. And if there is a cycle in the linked list they will meet both pointers will eventually meet.

A way to find out the middle element of a linked list is to use two pointers, one that moves one by one and another that moves two by two. Once the one that moves two nodes at a time reaches to the end, first node comes to the middle of the linked list.

To check if a given linked list is palindrome, divide the list into two parts. Reverse the first part and compare with the second part node by node. If they are equal that, linked list contains a palindrome. There are several different approaches to solve palindrome problem both recursively and iteratively.

Given two singly linked lists in sorted order, which forms a Y shape, you can reverse both of the linked lists and compare each element one by one by keeping two pointers. Once you reach the nodes that don’t intersect. Previous nodes are the intersection points.

Given a sorted singly linked, it s possible to remove the duplicates with a single iteration, by keeping two pointers, one to current node and one to the next node. If the next node is equal to current node, connect the current node to next node’s next node.

Given an unsorted singly linked list, it s possible to remove duplicates by using a dictionary. Store elements in the dictionary as you iterate the list. Each time you move to a node, check the dictionary, if the element is in the dictionary already, that s duplicate. Another way is to sort and do the above algorithm.

Given a linked list of even and odd numbers, you can separate the even numbers from the odd ones as follows. Using two pointers, one to point to the head and another to point to the tail, start iterating from both ends, if first pointer’s node is even and second pointer node is odd then swap them. Otherwise keep moving the pointers until you reach a odd or even number. Then swap them until two pointers overlap.

Given a linked list in which you need to set the last node as the head of the linked list. You traverse the linked list once. Once you reach to the end, you also keep a previous pointer to find the node that will qualify to last node. Last node next pointer will be assigned to the head pointer and then will qualify to be the head node. Tail node will be the second pointer node, whose next pointer will point to null.

Below is an implementation of a linked list that I have quickly written. Syntax hightlighter is not working perfect as you can see. Sorry about that.

using System;
using System.Collections;
using System.Collections.Generic;

namespace FiratAtagun.DataStructureTests.LinkedList
{
    public class Node : IEquatable where T : IComparable
    {
        public Node Next;

        public Node()
        {
        }

        public Node(T data)
        {
            Data = data;
        }

        public Node(Node data)
        {
            Data = data.Data;
        }

        public Node(T data, Node next)
        {
            Data = data;
            Next = next;
        }

        public T Data { set; get; }

        #region IEquatable Members

        public bool Equals(T other)
        {
            return Data.Equals(other);
        }

        #endregion
    }

    public enum InsertionMethod
    {
        Default,
        Recursive,
        Iterative
    }

    public class SinglyLinkedList : ICollection> where T : IComparable
    {
        private int _count;
        private Node _head;
        private Node _iterator;

        public SinglyLinkedList()
        {
        }

        public SinglyLinkedList(T data)
        {
            _head = new Node(data);
        }

        public SinglyLinkedList(Node node)
        {
            _head = node;
        }

        public SinglyLinkedList(IEnumerable collection)
        {
            foreach (T item in collection)
            {
                Insert(item);
            }
        }

        #region ICollection> Members

        public void Add(Node item)
        {
            Insert(item);
        }

        public void Clear()
        {
            _head = null;
        }

        public bool Contains(Node item)
        {
            Node found = Find(item);
            return found != null ? false : true;
        }

        public void CopyTo(Node[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        public int Count
        {
            get { return _count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(Node item)
        {
            return Delete(item);
        }

        public IEnumerator> GetEnumerator()
        {
            _iterator = _head;
            while (_iterator != null)
            {
                yield return _iterator;
                _iterator = _iterator.Next;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        public void Insert(T data, InsertionMethod insertionMethod = InsertionMethod.Default)
        {
            _count++;
            Insert(new Node(data), insertionMethod);
        }

        public void Insert(Node node, InsertionMethod insertionMethod = InsertionMethod.Default)
        {
            if (insertionMethod == InsertionMethod.Default || InsertionMethod.Iterative == insertionMethod)
            {
                InsertIteratively(node);
                return;
            }

            InsertRecursively(node);
        }

        private void InsertRecursively(Node node)
        {
            if (_head == null)
            {
                _head = node;
                return;
            }

            Node currentNode = _head;
            InsertRecursively(node, currentNode, null);
        }

        private void InsertRecursively(Node node, Node currentNode, Node previousNode)
        {
            if (currentNode != null)
            {
                InsertRecursively(node, currentNode.Next, currentNode);
                return;
            }

            currentNode = node;
            previousNode.Next = currentNode;
        }

        private void InsertIteratively(Node node)
        {
            if (_head == null)
            {
                _head = node;
                return;
            }

            Node currentNode = _head;

            while (currentNode.Next != null)
            {
                currentNode = currentNode.Next;
            }

            currentNode.Next = node;
        }

        public bool Delete(Node node)
        {
            return true;
        }

        public Node Find(T element)
        {
            foreach (var item in this)
            {
                if (element.Equals(item.Data))
                    return item;
            }
            return null;
        }

        public Node Find(Node node)
        {
            foreach (var element in this)
            {
                if (node.Data.Equals(element.Data))
                    return element;
            }
            return null;
        }

        public void InsertAfter(T data, Node node)
        {
        }

        public void InsertBefore(T data, Node node)
        {
        }

        public bool Replace(T data, Node node)
        {
            return true;
        }

        public bool Contains(T item)
        {
            return Contains(new Node(item));
        }
    }
}

MinHeap Implementation via C#

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: July 1, 2011

Heap data structure, Binary Heap, is quite useful to keep the min and max access in constant time,O(1). Moreover, Binary heaps can be used to implement priority queues.

Binary heap
implementation is quite easy. Below is the code for MinHeap . I need to add the HeapSort which is an efficient comparison based algorithm that takes O(nlogn) for sorting a sequence, Heap sort can be done in place. Basic idea behind Heap sort is to remove the minimum, then take the right most leaf (which is the last element in the array, due to the nature of this structure, which should be a complete tree) and then call heapify method each time after removing the min, removing n nodes takes O(n) time and for each node, we need to call heapify method which cost O(logn), hence overall running time of this algorithm is O(nlogn).

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

namespace FiratAtagun.DataStructures.Heap
{
    public class MinHeap : IEnumerable
    {

        private int[] _collection;
        private int _currentCapacity;
        private const int DefaultCapacity = 20;
        private int _index = 0;

        public MinHeap()
        {
            _collection = new int[DefaultCapacity];
            _currentCapacity = DefaultCapacity;
        }

        public int GetParent(int i, out int index)
        {
            double element = i;
            index = (int)Math.Floor((element - 1)  / 2);

            if(index < 0)
            {
                return 0;
            }

            return _collection[index];
        }

        public int GetLeftChild(int i, out int index)
        {
            index = (2 * i) + 1;
            return _collection[index];
        }

        public int GetRightChild(int i, out int index)
        {
            index = (2 * i) + 2;
            return _collection[index];
        }

        public void Insert(int i)
        {
            _collection[_index] = i;

            HeapifyUp(_index);
            _index++;
        }

        private int _currentIndex;

        private void HeapifyUp(int element)
        {
            int parentIndex;

            int parent = GetParent(element, out parentIndex);

            if (_collection[element] < parent)
            {
                Swap(ref _collection[parentIndex], ref _collection[element]);

            }
            else
            {
                return;
            }

            // Swapped, current element is at parentIndex now, and _index is the parent of the element

            HeapifyUp(parentIndex);

        }

        public void Swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }

        public int Count
        {
            get { return _index - 1; }
        }

        public int Minimum
        {
            get { return _collection[0]; }
        }

        public int ExtractMinimum()
        {
            int minimum = _collection[0];

            _collection[0] = _collection[--_index];
            _collection[_index] = default(int);

            Heapify();

            return minimum;
        }

        public void Heapify()
        {
            _currentIndex = 0;
            Heapify(_currentIndex);
        }

        public void Heapify(int index)
        {

            int leftChildIndex;
            int rightChildIndex;

            int leftChild = GetLeftChild(index, out leftChildIndex);
            int rightChild = GetRightChild(index, out rightChildIndex);

            if(leftChild == 0 && rightChild == 0)
            {
                return;
            }

            int replacingElement = 0;

            if (leftChild < rightChild)
            {
                replacingElement = leftChildIndex;
            }
            if (leftChild > rightChild)
            {
                replacingElement = rightChildIndex;
            }

            if (leftChild == rightChild)
            {
                replacingElement = leftChildIndex;
            }

            Swap(ref _collection[index], ref _collection[replacingElement]);

            Heapify(replacingElement);
        }

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            foreach (var i in _collection)
            {
                yield return i;
            }
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}

Reversal algorithm for array rotation

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: June 30, 2011

Given an array 1,2,3,4,5,6,7. You are asked to rotate the array so that output will be 3,4,5,6,7,8,1,2. How to do this? There is a very easy way to get this done.

Question: Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.

here is the pseudo code for it.

Reverse first d element,
reverse d+1 to n,
reverse the whole array
and voila.

Below is the code :

        public static void Rotate(int [] arr, int n)
        {
            RecursiveReverse(arr, 0, n-1);
            RecursiveReverse(arr, n, arr.Length-1);
            RecursiveReverse(arr, 0, arr.Length-1);
        }

        public static void RecursiveReverse(int [] arr, int start, int end)
        {
            if(start >= end)
            {
                return;
            }

            var temp = arr[end];
            arr[end] = arr[start];
            arr[start] = temp;

            RecursiveReverse(arr, start + 1, end-1);
        }

Maximum difference between two elements

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: June 30, 2011

Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].

Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

Obvious solution is using two for loops and checking the difference between every element to every other element which is O(n^2). You will need an additional variable to keep the max difference.

It is important to understand this question such that, you can only go from left to right, so we are not talking about absolute value difference. Therefore, sorting doesnt help.

A better solution is to keep two variables, one to keep the minimum element so far and another to keep the maximum difference so far. This allows a single iteratation over the array and you will have the answer.

Below is the code for it.

        public static void FindMaxDifference()
        {
            var arr = new int[] { 7, 9, 5, 6, 3, 20 };
            int min = arr[0];
            int maxSoFar = arr[1] - arr[0];
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] < min)
                {
                    min = arr[i];
                }
                if (arr[i] - min > maxSoFar)
                {
                    maxSoFar = arr[i] - min;
                }
            }
            Console.WriteLine(maxSoFar);
        }

Leaders in an array

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: June 30, 2011

Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.

This is a pretty simple algorithm, you need to scan the array from right to left and keep track of the maximum element, whenever you change the maximum, you find a leader, you print that.

        public static void FindLeadersInArray()
        {
            int[] arr = new[] { 16, 17, 4, 3, 5, 2 };

            int maxNow = 0;
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                if(arr[i] > maxNow)
                {
                    maxNow = arr[i];
                    Console.WriteLine(arr[i]);
                }
            }

        }

Sort elements by frequency

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: June 30, 2011

Print the elements of an array in the decreasing frequency if 2 numbers have same frequency then print the one which came 1st
E.g. 2 5 2 8 5 6 8 8 output: 8 8 8 2 2 5 5 6.
There are several approaches to this problem, such as sorting and counting the number of occurrence, sorting can be done in nlogn using quick sort, merge sort. etc. Also , you can use bucket sort for this kind of questions as well.

Below is a method that uses dictionary/hashtable, first, we need to iterate through the input and find the occurrences of all the elements. Then we need to sort the dictionary by value in descending order, which i used linq in the code below.

You can also use a binary search tree, you will need to modify the Node class, and add the count property to it, so if there is a duplicate, you will need to increment the count. Then you can do a inorder traversal to find the sorted sequence in ascending order then you need to reverse that.

        public static void SortByFrequency(int [] arr)
        {
            Dictionary numbersToOccurence = new Dictionary();

            foreach (var  item in arr)
            {
                int res = 0;

                if(numbersToOccurence.TryGetValue(item,out res))
                {
                    numbersToOccurence[item] = ++res;
                }else
                {
                    numbersToOccurence.Add(item, 1);
                }
            }

            var sorted = (from item in numbersToOccurence orderby item.Value descending select item).ToDictionary(kvpair => kvpair.Key, kvpair=>kvpair.Value);

            foreach (var i in sorted)
            {
                Console.WriteLine("Key : {0}, {1}",i.Key, i.Value);
            }

        }

Reversing an Array or string recursively and iteratively

Categories: Algorithms, Programming
Tags:
Comments: No Comments
Published on: June 30, 2011

It’s common to come across a requirement to reverse an array or string recursively or iteratively. Even though C# has a linq method that does this for you. It s a good practice to understand how reversing works.

There are several ways you can reverse a collections. Below are two approaches to reverse an array and string, since string is a character array, same approach applies to them.

        public static void RecursiveReverse(int [] arr, int start, int end)
        {
            if(start >= end)
            {
                return;
            }

            var temp = arr[end];
            arr[end] = arr[start];
            arr[start] = temp;

            RecursiveReverse(arr, start + 1, end-1);
        }

         public static string Reverse(string str)
        {
            if(String.IsNullOrEmpty(str))
            {
                return string.Empty;
            }

            char[] c_str = str.ToCharArray();

            for(int i = 0; i < str.Length / 2 ; i++)
            {

                var temp = c_str[i];

                c_str[i] = c_str[str.Length - i - 1];
                c_str[str.Length - i - 1] = temp;

            }

            return new string(c_str);
        }
page 1 of 9»

Welcome , today is Tuesday, February 7, 2012

Bad Behavior has blocked 250 access attempts in the last 7 days.