Skip to content

Tree Traversal using C# 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

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

namespace ParallelTreeTraversal
{
	class Node
	{
		public int Item { get; set; } 
		public Node LeftChild { get; set; }
		public Node RightChild { get; set; }
	}

	class Tree
	{
		private Node root;

		public Tree()
		{ 
			root = null; 
		}

		public Node ReturnRoot()
		{
			return root;
		}

		public void Insert(int id)
		{
			Node newNode = new Node();
			newNode.Item = id;

			if (root == null)
				root = newNode;
			else
			{
				Node current = root;
				Node parent;
				while (true)
				{
					parent = current;
					if (id < current.Item)
					{
						current = current.LeftChild;
						if (current == null)
						{
							parent.LeftChild = newNode;
							return;
						}
					}
					else
					{
						current = current.RightChild;
						if (current == null)
						{
							parent.RightChild = newNode;
							return;
						}
					}
				}
			}
		}

		public void Inorder(Node root, List<int> inorder)
		{
			if (root != null)
			{
				Inorder(root.LeftChild, inorder);
				inorder.Add(root.Item);
				Inorder(root.RightChild, inorder);
			}
		}

		public void Preorder(Node root, List<int> preorder)
		{
			if (root != null)
			{
				preorder.Add(root.Item);
				Preorder(root.LeftChild, preorder);
				Preorder(root.RightChild, preorder);
			}
		}

		public void Postorder(Node root, List<int> postorder)
		{
			if (root != null)
			{
				Postorder(root.LeftChild, postorder);
				Postorder(root.RightChild, postorder);
				postorder.Add(root.Item);
			}
		}

		// By using Parallel.Invoke 
		public void TraverseTree(Tree tree)
		{
			List<int> inorder = new List<int>();
			List<int> preorder = new List<int>();
			List<int> postorder = new List<int>();

			Parallel.Invoke(
				() => {
					tree.Inorder(tree.ReturnRoot(), inorder);
				},
				() => {
					tree.Preorder(tree.ReturnRoot(), preorder);
				},
				() => {
					tree.Postorder(tree.ReturnRoot(), postorder);
				}
			);

			Console.WriteLine("Inorder traversal resulting Tree Sort");
			foreach (int item in inorder)
			{
				Console.Write(item + " ");
			}
			Console.WriteLine(" ");

			Console.WriteLine("Preorder traversal");
			foreach (int item in preorder)
			{
				Console.Write(item + " ");
			}
			Console.WriteLine(" ");

			Console.WriteLine("Postorder traversal");
			foreach (int item in postorder)
			{
				Console.Write(item + " ");
			}
			Console.WriteLine(" ");
		}
	}

	class Program
	{
		public static void Main(string[] args)
		{
			Tree theTree = new Tree();
			theTree.Insert(42);
			theTree.Insert(25);
			theTree.Insert(65);
			theTree.Insert(12);
			theTree.Insert(37);
			theTree.Insert(13);
			theTree.Insert(30);
			theTree.Insert(43);
			theTree.Insert(87);
			theTree.Insert(99);
			theTree.Insert(9);

			theTree.TraverseTree(theTree);

			Console.ReadLine();
		}
	}
}

OUTPUT:

Inorder traversal resulting Tree Sort
9 12 13 25 30 37 42 43 65 87 99
Preorder traversal
42 25 12 9 13 37 30 65 43 87 99
Postorder traversal
9 13 12 30 37 25 43 99 87 65 42

If you found the article useful, please rate the article below. Thanks !

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<char, int> dict1, dict2 = new Dictionary<char, int>();

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

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

public static Dictionary<char, int> StringDictionary(string str)
{
    return str.GroupBy(s => s).ToDictionary(d => d.Key, d => 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<char, int> dict1, dict2 = new SortedDictionary<char, int>();

	dict1 = StringDictionary(str1);

	dict2 = StringDictionary(str2);

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

	Console.ReadKey();
}

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

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

Group a type with DateTime member based on the split of a year as quarterly/half yearly using C# and LINQ

In this post there is code to classify a type employee with members name and joindate into a particular quarter of a year based on their joining date.

You can run the code on linqpad or VS.

If you want to classify it on half yearly basis change GroupBy(o => (o.joindate.Month – 1) / 3) to
GroupBy(o => (o.joindate.Month – 1) / 6)

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

namespace DateFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emp = new List<Employee>()
			{ 
				new Employee 
				{ 
					name = "Steve", joindate = DateTime.Parse("3/28/2012", System.Globalization.CultureInfo.InvariantCulture)
				},
				new Employee 
				{ 
					name = "John", joindate = DateTime.Parse("5/28/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Chin", joindate = DateTime.Parse("12/21/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Henry", joindate = DateTime.Parse("12/25/2012", System.Globalization.CultureInfo.InvariantCulture) 
				}
			};

            // uncomment lines below to view the dump on linqpad (pasted below)
            /*emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList()).Dump();*/

            var query = emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList());

            foreach (KeyValuePair<int, List<Employee>> kvp in query)
            {
                Console.WriteLine(kvp.Key.ToString());

                foreach (Employee employee in kvp.Value)
                {
                    Console.WriteLine(employee.name);
                }
            }

            Console.ReadKey();
        }
    }

    class Employee
    {
        public string name { get; set; }
        public DateTime joindate { get; set; }
    }
}

This is a snapshot from linqpad. The key value 0,1,2 and 3 are the quarters. This helped me get a report of employees hired on a quarterly basis.

datefilter

Originally posted on TechCrunch:

Editor’s note:Phil Freo leads the engineering team at ElasticSales. Previously he was at Quizlet and Google. Follow him on Twitter.

There is often confusion about the various roles of a web engineering team. I have had to explain, even to technical recruiters, the differences between these roles and that the lines that separate them are often fuzzy. I thought I’d share the framework I like to use to evaluate whether someone is a good fit for a startup’s technical team.

In a startup, you can’t afford to have people who are only able to do one thing. Someone could be adept at writing HTML/CSS, but if they don’t have a great eye for design or know JavaScript well, it’s just not worth having them on the core team. Similarly, somebody who knows a little bit of everything but isn’t advanced in anything will just drag the team down.

The size…

View original 760 more words