ISourceCode

Make the frequent cases fast and the rare case correct

Determine if a string has all unique characters


class Program
{
    static void Main(string[] args)
    {
        string name = "hello";

        char[] characters = name.ToCharArray();

        Dictionary<char, int> dict = new Dictionary<char, int>();

        int count = 0;

        foreach (var x in characters)
        {
            if (dict.ContainsKey(x))
            {
                dict[x] = dict[x] + 1;
            }
            else
            {
                dict.Add(x, count+1);
            }
        }

        foreach (var kvp in dict)
        {
            Console.WriteLine(kvp.Key + " " + kvp.Value);

            if (kvp.Value > 1)
            {
                Console.WriteLine("String does not have all unique characters");
            }
        }

        Console.ReadKey();
    }
}

C# – Writing an Extension Method

A simple extension method that extends the List class. The extension method accepts a Func delegate. The algorithm is to multiply each element in the list by 2. The Func delegate points to this algorithm method.

using System;
using System.Collections.Generic;

namespace ExtensionMethodFunc
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();

            for (int i = 1; i <= 10; i++)
                list.Add(i);

            // Approach 1 to call the extension method with the Func delegate
            foreach (int i in list.GetMyList(MultiplyByTwo))
                Console.WriteLine(i);

            // Approach 2, Func delegate explicitly declared pointing to the method
            //Func<int, int> algo = MultiplyByTwo;
            //foreach (int i in list.GetMyList(algo))
            //	Console.WriteLine(i);

            // Approach 3, using an anonymous method, C# 2.0 feature
            //Func<int, int> algo = delegate(int x) { return x * 2; };
            //foreach (int i in list.GetMyList(algo))
            //  Console.WriteLine(i);

            // Approach 4, using lambda expression which is an anonymous function
            // C# 3.0 feature
            //Func<int, int> algo = x => x * 2;
            //foreach (int i in list.GetMyList(algo))
            //	Console.WriteLine(i);

            // Approach 5, using lambda expression without explicitly declaring a func
            //foreach (int i in list.GetMyList(m => m * 2))
            //	Console.WriteLine(i);

            // Approach 6, redundant lambda calling original method, not to be used
            //Func<int, int> algo = x => MultiplyByTwo(x);
            //foreach (int i in list.GetMyList(algo))
            //    Console.WriteLine(i);

            Console.ReadKey();
        }

        private static int MultiplyByTwo(int value)
        {
            return value * 2;
        }
    }

    static class ExtensionMethods
    {
        // Non generic implementation of extension method
        //
        //public static IEnumerable<int> GetMyList(this IEnumerable<int> list, Func<int, int> selector)
        //{
        //	foreach (int item in list)
        //		yield return selector(item);
        //}

        public static IEnumerable<TResult> GetMyList<TSource, TResult>(this IEnumerable<TSource> list, 
            Func<TSource, TResult> selector)
        {
            foreach (TSource item in list)
                yield return selector(item);
        }
    }
}

C# – Tree Traversal using Parallel.Invoke Method.

Used the Parallel.Invoke method from Task Parallel library.

Invoke(Action[]) executes the tasks possibly in parallel.

Pass a list of actions to the method.

I already had a tree and i plugged this method.For more check this article

Read more of this post

C# – code optimization – Decimal value computation

public Decimal(
	int lo,
	int mid,
	int hi,
	bool isNegative,
	byte scale
)
//Fill in with any amount, no decimal present but implied (e.g. 500 represents $5.00)
var st = new Stopwatch();

st.Start();
 for (ulong ulongAmount = 10000000; ulongAmount < 20000000; ulongAmount++)
 {
 // Optimized ulongAmount / 100m
 decimal amount = new Decimal((int)ulongAmount, (int)(ulongAmount >> 32), 0, false, 2); 
 }
 st.Stop();
 st.Dump();

st.Reset();

 st.Start();
 for (ulong ulongAmount = 10000000; ulongAmount < 20000000; ulongAmount++)
 {
 decimal amount = ulongAmount / 100m;
 }
 st.Stop();
 st.Dump();

Image

C# – LINQ – Check if two strings are Anagrams using Dictionary data structure

Below is code written in C# and LINQ to check if two strings are anagram of each other using the .NET Dictionary class which is a hash table.

Ordering the dictionary according to the key in order to do a SequenceEqual might not be elegant since a dictionary is meant to be unordered ( take a look at the dump).

Execute it using Linqpad.

static void Main()
{
    string str1 = "ab# wrr2b";
    string str2 = "b#rba2 rw";

    Dictionary&lt;char, int&gt; dict1, dict2 = new Dictionary&lt;char, int&gt;();

    dict1 = StringDictionary(str1);
    dict2 = StringDictionary(str2);

    if (dict1.OrderBy(d =&gt; d.Key).SequenceEqual(dict2.OrderBy(d =&gt; d.Key)))
    {
        Console.WriteLine("True");
    }
    else Console.WriteLine("False");
}

public static Dictionary&lt;char, int&gt; StringDictionary(string str)
{
    return str.GroupBy(s =&gt; s).ToDictionary(d =&gt; d.Key, d =&gt; d.Count()).Dump();
}

OUTPUT:

anagramcheck

Alternatively SortedDictionary class can also be used

static void Main(string[] args)
{
	string str1 = "ab# wrr2b";
	string str2 = "b#rba2 r";

	SortedDictionary&lt;char, int&gt; dict1, dict2 = new SortedDictionary&lt;char, int&gt;();

	dict1 = StringDictionary(str1);

	dict2 = StringDictionary(str2);

	if (dict1.SequenceEqual(dict2))
	{
		Console.WriteLine("True");
	}
	else Console.WriteLine("False");

	Console.ReadKey();
}

public static SortedDictionary&lt;char, int&gt; StringDictionary(string str)
{
	return new SortedDictionary&lt;char, int&gt;(str.GroupBy(s =&gt; s).ToDictionary(d =&gt; d.Key, d =&gt; d.Count()));
}

Couple of years ago i wrote an article about the same algorithm and coded in C++ and Java.

    class Program
    {
        static void Main(string[] args)
        {
            string one = "hello";
            string two = "hellol";

            char[] first = one.ToCharArray();
            char[] second = two.ToCharArray();

            Dictionary<char, int> string1 = new Dictionary<char, int>();
            Dictionary<char, int> string2 = new Dictionary<char, int>();

            int count = 0;

            foreach (var x in first)
            {
                if (string1.ContainsKey(x))
                {
                    string1[x] = string1[x] + 1;
                }
                else
                {
                    string1.Add(x, count+1);
                }
                
            }

            count = 0;

            foreach (var x in second)
            {
                if (string2.ContainsKey(x))
                {
                    string2[x] = string2[x] + 1;
                }
                else
                {
                    string2.Add(x, count + 1);
                }

            }

            foreach (var kvp in string1)
            {
                Console.WriteLine(kvp.Key + " " + kvp.Value);
            }

            foreach (var kvp in string2)
            {
                Console.WriteLine(kvp.Key + " " + kvp.Value);
            }

            //if (string1.OrderBy(d => d.Key).SequenceEqual(string2.OrderBy(d => d.Key)))
            //{
            //    Console.WriteLine("True");
            //}
            //else Console.WriteLine("False");

            foreach (var kvp in string1)
            {
                if (!string2.ContainsKey(kvp.Key))
                {
                    Console.WriteLine("Not anagram");
                }

                if (string2.ContainsKey(kvp.Key))
                {
                    if (kvp.Value != string2[kvp.Key])
                    {
                        Console.WriteLine("No, Not an Anagram");
                    }
                }
            }

            Console.ReadKey();
        }
    }
Follow

Get every new post delivered to your Inbox.

Join 30 other followers