Tuesday, July 31, 2018

Algorithm to Remove character from string

Remove char from String :- Consider the requirement to strip invalid characters from a string. The characters just need to be removed and replace with blank or string.Empty.

Using Array

private static void RemoveCharFromStr(string source, char chr)
        {
            var pool = new char[source.Length];
            int poolCount = 0;
            for (int i = 0; i < source.Length; i++)
            {
                if (source[i] != chr)
                {
                    pool[poolCount] = source[i];
                    poolCount++;
                }
            }
            Console.WriteLine(new string(pool));
        }


Using Replace

source.Replace(str, string.Empty)


RemoveCharFromFirstStr :-

 private static void RemoveCharFromFirstStr()
        {
            string first = "char";
            string second = "Remove char from";

            var pool = new char[first.Length];
            int count = 0;
            for (int i = 0; i <first.Length; i++)
            {
                bool isfound = false;
                foreach (var c in second)
                {
                    if (first[i] == c)
                    {
                        isfound = true;
                        break;
                    }
                }
                if (!isfound)
                {
                    pool[count] = first[i];
                    count++;
                }
            }
            Console.WriteLine(new string(pool));

        }


Algorithm to Convert number string to Integer and Anagram String

StringToInt :-  Algrothim to convert number string into integer.

public static void StringToInt(string source)
        {
            string lookUpValue = "0123456789";
            int total = 0;
            foreach (char c in source)
            {
                if (lookUpValue.Contains(c))
                {
                    total = (total * 10) + lookUpValue.IndexOf(c);
                }
            }
            Console.WriteLine(total);

Anagram :- words are said to be Anagrams of each other if they share the same set of letters to form the respective words. Remember, it’s just rearranging the existing letter.

private static void StrAnagram(string str1, string str2)
        {
            //One way
            if (str1.Length == str2.Length)
            {
                var char1 = str1.ToLower().ToCharArray();
                var char2 = str2.ToLower().ToCharArray();
                Array.Sort(char1);
                Array.Sort(char2);
                str1 = new string(char1);
                str2 = new string(char2);

                if(str1 == str2)
                    Console.WriteLine(true);
                else
                {
                    Console.WriteLine(false);
                }
            }
}

Palindrome String and Int Algorithm

Palindrome String :- Palindromes can be read in both directions. How can you determine if a string is a palindrome in the C# language?

 Below is the code to find string is palindrome 

public static void PalindromeStr(string source)
        {
            var reverse = source.ToCharArray();
            Array.Reverse(reverse);
            if(new string(reverse) == source)
                Console.WriteLine(true);
        }

Palindrome Int :- Palindromic number or numeral Palindrome is a number, which remains the same when its digits are reversed. Like 1234321, for example, it is “symmetrical”.

To check if number is palindrome, Use below code

public static void PalindromeInt(int source)
        {
            var value = source;
            int reverse = 0;
            while (value > 0 )
            {
                int remainder = value % 10;
                reverse = (reverse * 10) + remainder;

                value = value / 10;
            }

            if(reverse == source)
                Console.WriteLine(true);
        }



Sunday, July 29, 2018

String Search Algorithm


This article does not attempt to teach you how to write high performance string matching algorithms, nor does it try to explain the algorithms that are presented. If you're looking for that kind of information, consult an algorithms book such as Knuth or Cormen, et al. An excellent online reference for string matching algorithms is the Handbook of Exact String Matching Algorithms.

Using in code 


1. Naive Search Algorithm 

Slide the pattern over text one by one and check for a match. If a match is found, then slides by 1 again to check for subsequent matches.


Example :- 

public static int[] SearchString(string str, string pat)
        {
            List<int> retVal = new List<int>();
            int M = pat.Length;
            int N = str.Length;

            for (int i = 0; i <= N - M; i++)
            {
                int j;

                for (j = 0; j < M; j++)
                {
                    if (str[i + j] != pat[j])
                        break;
                }

                if (j == M)
                    retVal.Add(i);
            }

            return retVal.ToArray();

        }


static void Main(string[] args)

        {
            string str = "String Search Algorithm in c#";

            var searchStr = "Algo";
int[] value = SearchString(str, searchStr);
        }


2. Boyer-Moore String Search Algorithm :- Unlike the previous pattern searching algorithms, algorithm starts matching from the last character of the pattern. This algorithm considered as the most efficient string-matching algorithm in usual applications.

Example

public static int[] SearchStringByBoyer(string str, string searchStr)
        {
            List<int> retVal = new List<int>();
            int m = searchStr.Length;
            int n = str.Length;

            int[] badChar = new int[256];

            BadCharHeuristic(searchStr, m, ref badChar);

            int s = 0;
            while (s <= (n - m))
            {
                int j = m - 1;

                while (j >= 0 && searchStr[j] == str[s + j])
                    --j;

                if (j < 0)
                {
                    retVal.Add(s);
                    s += (s + m < n) ? m - badChar[str[s + m]] : 1;
                }
                else
                {
                    s += Math.Max(1, j - badChar[str[s + j]]);
                }
            }

            return retVal.ToArray();
        }
       
        private static void BadCharHeuristic(string str, int size, ref int[] badChar)
        {
            int i;

            for (i = 0; i < 256; i++)
                badChar[i] = -1;

            for (i = 0; i < size; i++)
                badChar[(int)str[i]] = i;
        }

static void Main(string[] args)
        {
            string str = "String Search Algorithm in c#";
            var searchStr = "Algo";
int[] value = SearchString(str, searchStr);

       }

IndexOf :- We can use IndexOf function of string to search the substring in string.

Example:- 

static void Main(string[] args)
        {
            string str = "String Search Algorithm in c#";
            var searchStr = "Algo";
             int minIndex = str.IndexOf(search);
            while (minIndex !=-1)
            {
                Console.WriteLine(minIndex.ToString());
                minIndex = str.IndexOf(search, minIndex + search.Length);
            }





Sorting Algorithm in C#


In this section, we’re going to take a look at a number of well-known sorting algorithms with the hope of sensitizing you to the notion of performance–a topic that is covered in greater detail in courses such as algorithms and data structures.

Bubble Sort :-  The bubble is the very common technique for beginners. It is easy to implement and understand. In bubble sort, each element of the unsorted list is compared to the next element and if the value of first element is greater than the value of the second element, then they are swapped.

Example :- 

Public static void BubbleShort()
        {
            var intArray = new int[5] {3, 21, 4, 8, 6};
            int temp;

            for (int i = 1; i <= intArray.Length; i++)
            {
                for (int j = 0; j < intArray.Length - i; j++)
                {
                    if (intArray[j] > intArray[j + 1])
                    {
                        temp = intArray[j];
                        intArray[j] = intArray[j + 1];
                        intArray[j + 1] = temp;
                    }
                }
            }
            foreach (var i in intArray)
            {
                Console.WriteLine(i);
            }

        }

Insertion Sort :- In the Insertion Sort algorithm, we build a sorted list from the bottom of the array. We repeatedly insert the next element into the sorted part of the array by sliding it down to its proper position.

This will require as many exchanges as Bubble Sort, since only one inversion is removed per exchange. So Insertion Sort also requires O(N2)exchanges. On average Insertion Sort requires only half as many comparisons as Bubble Sort, since the average distance an element must move for random input is one-half the length of the sorted portion.

Public static void InsertionSort()
        {
            var inArray = new int[6] {1, 4, 6, 67, 78, 9};
            int temp;
            for (int i = 0; i < inArray.Length -1; i++)
            {
                for (int j = i + 1; j >0 ; j--)
                {
                    if (inArray[j- 1] > inArray[j])
                    {
                        temp = inArray[j -1];
                        inArray[j - 1] = inArray[j];
                        inArray[j] = temp;
                    }
                }
            }

            foreach (var array in inArray)
            {
                Console.WriteLine(array);
            }

        }


Selection Sort :-  Here Selection sort is an algorithm of sorting an array where it loop from the start of the loop, and check through other elements to find the minimum value. After the end of the first iteration, the minimum value is swapped with the current element. The iteration then continues from the 2nd element and so on.

public static void SelectionSort()
        {
            var inArray = new int[6] { 1, 4, 6, 67, 78, 9 };
            int temp;
            for (int i = 0; i < inArray.Length; i++)
            {
                for (int j = i + 1; j < inArray.Length; j++)
                {
                    if (inArray[i] > inArray[j])
                    {
                        temp = inArray[j];
                        inArray[j] = inArray[i];
                        inArray[i] = temp;
                    }
                }
            }

            foreach (var array in inArray)
            {
                Console.WriteLine(array);
            }

        }

Quick and Merge Sort example will be published in next blog.

Friday, July 27, 2018

MongoDB with C#: finding elements with custom predicate

Pass Lambda expression as parameter to filter data from mongodb collection. 
Your data filter function could be

public IEnumerable<BsonDocument> FindAllWithPredicate(Func<BsonDocument, bool> condition)
{
    return Collection.AsQueryable().Where(condition).ToArray();
}

Predicatebuilder.cs

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>()
    {
        return f => true;
    }

    public static Expression<Func<T, bool>> False<T>()
    {
        return f => false;
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}  
Generate lambda expression by predicate builder
public static class PredicateBuilderStore
{
    public static Func<BsonDocument, bool> GetPredicateForBsonDocument(Entity entity)
    {
        var predicate = PredicateBuilder.True<BsonDocument>();            
        predicate = predicate.And(d => d.GetElement({key}).Value == CompareWithValue);
        return predicate.Compile();
    }   
}
if you want to query just all items, you could do it as:

return this.collection.Find(_=>true).ToArray();

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...