juin

21

Posted by : admin | On : 21 juin 2016

In this article we’ll demontrate usage of graph , binary trees , and tree

As well as BFS (common neighor first search before doing a drill down on the first node ) and dFS (deep search ) pattern

Common Tree

using System;
using System.Collections.Generic;

public class TreeNode<T>
{
	private T value;
	private bool hasParent;
	private List<TreeNode<T>> children;

	public TreeNode(T value)
	{
		if (value == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}
		this.value = value;
		this.children = new List<TreeNode<T>>();
	}

	public T Value
	{
		get{return this.value;}
		set{this.value = value;}
	}

	public int ChildrenCount
	{
		get{return this.children.Count;}
	}

	public void AddChild(TreeNode<T> child)
	{
		if (child == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}

		if (child.hasParent)
		{
			throw new ArgumentException("The node already has a parent!");
		}
		child.hasParent = true;
		this.children.Add(child);
	}

	public TreeNode<T> GetChild(int index)
	{
		return this.children[index];
	}
}

public class Tree<T>
{
	private TreeNode<T> root;

	public Tree(T value)
	{
		if (value == null)
		{
			throw new ArgumentNullException("Cannot insert null value!");
		}
		this.root = new TreeNode<T>(value);
	}

	public Tree(T value, params Tree<T>[] children) : this(value)
	{
		foreach (Tree<T> child in children)
		{
			this.root.AddChild(child.root);
		}
	}

	/// <summary>
	/// The root node or null if the tree is empty
	/// </summary>
	public TreeNode<T> Root
	{
		get{return this.root;}
	}

	private void TraverseDFS(TreeNode<T> root, string spaces)
	{
		if (this.root == null)
		{
			return;
		}

		Console.WriteLine(spaces + root.Value);

		TreeNode<T> child = null;
		for (int i = 0; i < root.ChildrenCount; i++)
		{
			child = root.GetChild(i);
			TraverseDFS(child, spaces + "   ");
		}
	}

	public void TraverseDFS()
	{
		this.TraverseDFS(this.root, string.Empty);
	}

	public void TraverseBFS()
	{
		Queue<TreeNode<T>> queue = new Queue<TreeNode<T>>();
		queue.Enqueue(this.root);
		while (queue.Count > 0)
		{
			TreeNode<T> currentNode = queue.Dequeue();
			Console.Write("{0} ", currentNode.Value);
			for (int i = 0; i < currentNode.ChildrenCount; i++)
			{
				TreeNode<T> childNode = currentNode.GetChild(i);
				queue.Enqueue(childNode);
			}
		}
	}

	public void TraverseDFSWithStack()
	{
		Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>();
		stack.Push(this.root);
		while (stack.Count > 0)
		{
			TreeNode<T> currentNode = stack.Pop();
			Console.Write("{0} ", currentNode.Value);
			for (int i = 0; i < currentNode.ChildrenCount; i++)
			{
				TreeNode<T> childNode = currentNode.GetChild(i);
				stack.Push(childNode);
			}
		}
	}
}

public static class TreeExample
{
	static void Main()
	{
		Tree<int> tree =
			new Tree<int>(7,
				new Tree<int>(19,
					new Tree<int>(1),
					new Tree<int>(12),
					new Tree<int>(31)),
				new Tree<int>(21),
				new Tree<int>(14,
					new Tree<int>(23),
					new Tree<int>(6))
			);

		Console.WriteLine("Depth-First Search (DFS) traversal (recursive):");
		tree.TraverseDFS();
		Console.WriteLine();

		Console.WriteLine("Breadth-First Search (BFS) traversal (with queue):");
		tree.TraverseBFS();
		Console.WriteLine();

		Console.WriteLine();
		Console.WriteLine("Depth-First Search (DFS) traversal (with stack):");
		tree.TraverseDFSWithStack();
		Console.WriteLine();
        Console.Read();
	}
}

Binary Tree

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

namespace AutoTest
{
    public class BinarySearchTree<T> where T : IComparable<T>
    {
        private BinaryTreeNode<T> root;
        public BinarySearchTree()
        {
            this.root = null;
        }
        public void Insert(T value)
        {
            this.root = Insert(value, null, root);
        }
        private BinaryTreeNode<T> Insert(T value,BinaryTreeNode<T> parentNode, BinaryTreeNode<T> node)
        {
            if (node == null)
            {
                node = new BinaryTreeNode<T>(value);
                node.parent = parentNode;
            }
            else
            {
                int compareTo = value.CompareTo(node.value);
                if (compareTo < 0)
                {
                    node.leftChild =Insert(value, node, node.leftChild);
                }
                else if (compareTo > 0)
                {
                    node.rightChild =Insert(value, node, node.rightChild);
                }
            }
            return node;
        }
        private BinaryTreeNode<T> Find(T value)
        {
            BinaryTreeNode<T> node = this.root;
            while (node != null)
            {
                int compareTo = value.CompareTo(node.value);
                if (compareTo < 0)
                {
                    node = node.leftChild;
                }
                else if (compareTo > 0)
                {
                    node = node.rightChild;
                }
                else
                {
                    break;
                }
            }
            return node;
        }
        public void PrintTreeDFS()
        {
            PrintTreeDFS(this.root);
            Console.WriteLine();
        }
        private void PrintTreeDFS(BinaryTreeNode<T> node)
        {
            if (node != null)
            {
                PrintTreeDFS(node.leftChild);
                Console.Write(node.value + " ");
                PrintTreeDFS(node.rightChild);
            }
        }
        internal class BinaryTreeNode<T> : IComparable<BinaryTreeNode<T>> where T : IComparable<T>
        {
            // Contains the value of the node
            internal T value;

            // Contains the parent of the node
            internal BinaryTreeNode<T> parent;

            // Contains the left child of the node
            internal BinaryTreeNode<T> leftChild;

            // Contains the right child of the node
            internal BinaryTreeNode<T> rightChild;

            /// <summary>Constructs the tree node</summary>
            /// <param name="value">The value of the tree node</param>
            public BinaryTreeNode(T value)
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Cannot insert null value!");
                }
                this.value = value;
                this.parent = null;
                this.leftChild = null;
                this.rightChild = null;
            }
            public override string ToString()
            {
                return this.value.ToString();
            }
            public override int GetHashCode()
            {
                return this.value.GetHashCode();
            }

            public override bool Equals(object obj)
            {
                BinaryTreeNode<T> other = (BinaryTreeNode<T>)obj;
                return this.CompareTo(other) == 0;
            }

            public int CompareTo(BinaryTreeNode<T> other)
            {
                return this.value.CompareTo(other.value);
            }
        }
    }
}

Graphe

using System;
using System.Collections.Generic;

public class Graph
{
	internal const int MaxNode = 1024;
	private int[][] childNodes;

	public Graph(int[][] childNodes)
	{
		this.childNodes = childNodes;
	}

	public void TraverseBFS(int node)
	{
		bool[] visited = new bool[MaxNode];
		Queue<int> queue = new Queue<int>();
		queue.Enqueue(node);
		visited[node] = true;
		while (queue.Count > 0)
		{
			int currentNode = queue.Dequeue();
			Console.Write("{0} ", currentNode);
			foreach (int childNode in childNodes[currentNode])
			{
				if (!visited[childNode])
				{
					queue.Enqueue(childNode);
					visited[childNode] = true;
				}
			}
		}
	}

	public void TraverseDFS(int node)
	{
		bool[] visited = new bool[MaxNode];
		Stack<int> stack = new Stack<int>();
		stack.Push(node);
		visited[node] = true;
		while (stack.Count > 0)
		{
			int currentNode = stack.Pop();
			Console.Write("{0} ", currentNode);
			foreach (int childNode in childNodes[currentNode])
			{
				if (!visited[childNode])
				{
					stack.Push(childNode);
					visited[childNode] = true;
				}
			}
		}
	}

	public void TraverseDFSRecursive(int node, bool[] visited)
	{
		if (!visited[node])
		{
			visited[node] = true;
			Console.Write("{0} ", node);
			foreach (int childNode in childNodes[node])
			{
				TraverseDFSRecursive(childNode, visited);
			}
		}
	}
}

class GraphExample
{
	static void Main()
	{
		Graph g = new Graph(new int[][] {
			new int[] {3, 6}, // successors of vertice 0
			new int[] {2, 3, 4, 5, 6}, // successors of vertice 1
			new int[] {1, 4, 5}, // successors of vertice 2
			new int[] {0, 1, 5}, // successors of vertice 3
			new int[] {1, 2, 6}, // successors of vertice 4
			new int[] {1, 2, 3}, // successors of vertice 5
			new int[] {0, 1, 4}  // successors of vertice 6
		});

		Console.Write("Breadth-First Search (BFS) traversal: ");
		g.TraverseBFS(0);
		Console.WriteLine();

		Console.Write("Depth-First Search (DFS) traversal (with stack): ");
		g.TraverseDFS(0);
		Console.WriteLine();

		Console.Write("Depth-First Search (DFS) traversal (recursive): ");
		bool[] visited = new bool[Graph.MaxNode];
		g.TraverseDFSRecursive(0, visited);
		Console.WriteLine();
	}
}

Good tuto

http://www.introprogramming.info/tag/graph-implementation/#_Toc362296541

jan

11

Posted by : admin | On : 11 janvier 2016

 

 

demo NVelocity

 

using NVelocityTemplateEngine.Engines;
using NVelocityTemplateEngine.Interfaces;

namespace NVelocityTemplateEngine
{
	/// <summary>
	/// Summary description for NVelocityEngineFactory.
	/// </summary>
	public class NVelocityEngineFactory
	{
		/// <summary>
		/// Creates a new instance of NVelocityFileEngine class.
		/// </summary>
		/// <param name="templateDirectory">The template directory.</param>
		/// <param name="cacheTemplate">if set to <c>true</c> [cache template].</param>
		/// <returns></returns>
		public static INVelocityEngine CreateNVelocityFileEngine(string templateDirectory, bool cacheTemplate)
		{
			return new NVelocityFileEngine(templateDirectory, cacheTemplate);
		}

		/// <summary>
		/// Creates a new instance of NVelocityAssemblyEngine class.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly.</param>
		/// <param name="cacheTemplate">if set to <c>true</c> [cache template].</param>
		/// <returns></returns>
		public static INVelocityEngine CreateNVelocityAssemblyEngine(string assemblyName, bool cacheTemplate)
		{
			return new NVelocityAssemblyEngine(assemblyName, cacheTemplate);
		}

		/// <summary>
		/// Creates a new instance of NVelocityMemoryEngine class.
		/// </summary>
		/// <param name="cacheTemplate">if set to <c>true</c> [cache template].</param>
		/// <returns></returns>
		public static INVelocityEngine CreateNVelocityMemoryEngine(bool cacheTemplate)
		{
			return new NVelocityMemoryEngine(cacheTemplate);
		}
	}
}
//=============================================================================
// Project : NVelocity wrapper
// Author  : Simone Busoli
// Updated : Thu 09/02/2006 01:35:00
// Compiler: Microsoft Visual C# .NET
//
// This code may be used in compiled form in any way you desire.  This
// file may be redistributed by any means in modified or unmodified form
// PROVIDING that this notice and the author's name and any copyright
// notices remain intact.
//
// This file is provided "as is" with no warranty either express or
// implied.  The author accepts no liability for any damage or loss of
// business that this product may cause.
//
// Version   Date        Who            Comments
// ============================================================================
// 1.0.0     09/02/2006  Simone Busoli  First release
//=============================================================================

using System.Reflection;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("NVelocityTemplateEngine")]
[assembly: AssemblyDescription("A wrapper for NVelocity template engine.")]
[assembly: AssemblyCompany("Simone Busoli")]
[assembly: AssemblyVersion("1.0.0.0")]
using System.Collections;
using System.IO;
using NVelocity;
using NVelocity.Exception;
using NVelocity.Runtime;
using NVelocityTemplateEngine.BaseClasses;
using NVelocityTemplateEngine.Interfaces;

namespace NVelocityTemplateEngine.Engines
{
	/// <summary>
	/// Summary description for NVelocityAssemblyEngine.
	/// </summary>
	public sealed class NVelocityAssemblyEngine : NVelocityEngineBase, INVelocityEngine
	{
		private string assemblyName;

		/// <summary>
		/// Initializes a new instance of the <see cref="NVelocityAssemblyEngine"/> class.
		/// </summary>
		/// <param name="assemblyName">Name of the assembly.</param>
		/// <param name="cacheTamplate">if set to <c>true</c> [cache tamplate].</param>
		internal NVelocityAssemblyEngine(string assemblyName, bool cacheTamplate) : base(cacheTamplate)
		{
			this.assemblyName = assemblyName;

			this.SetProperty(RuntimeConstants.RESOURCE_LOADER, "assembly");
			this.SetProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader;NVelocity");
			this.SetProperty("assembly.resource.loader.assembly", assemblyName);
			this.Init();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="templateName">Name of the template.</param>
		/// <returns></returns>
		public string Process(IDictionary context, string templateName)
		{
			StringWriter writer = new StringWriter();

			try
			{
				Template template = this.GetTemplate(this.assemblyName + "." + templateName);
				template.Merge(CreateContext(context), writer);
			}
			catch (ResourceNotFoundException rnf)
			{
				return rnf.Message;
			}
			catch (ParseErrorException pe)
			{
				return pe.Message;
			}

			return writer.ToString();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="writer">The writer.</param>
		/// <param name="templateName">Name of the template.</param>
		public void Process(IDictionary context, TextWriter writer, string templateName)
		{
			try
			{
				Template template = this.GetTemplate(this.assemblyName + "." + templateName);
				template.Merge(CreateContext(context), writer);
			}
			catch (ResourceNotFoundException rnf)
			{
				writer.Write(rnf.Message);
			}
			catch (ParseErrorException pe)
			{
				writer.Write(pe.Message);
			}
		}
	}
}
using System.Collections;
using System.IO;
using NVelocity;
using NVelocity.Exception;
using NVelocity.Runtime;
using NVelocityTemplateEngine.BaseClasses;
using NVelocityTemplateEngine.Interfaces;

namespace NVelocityTemplateEngine.Engines
{
	/// <summary>
	/// Summary description for NVelocityFileEngine.
	/// </summary>
	public sealed class NVelocityFileEngine : NVelocityEngineBase, INVelocityEngine
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="NVelocityFileEngine"/> class.
		/// </summary>
		/// <param name="templateDirectory">The template directory.</param>
		/// <param name="cacheTemplate">if set to <c>true</c> [cache template].</param>
		internal NVelocityFileEngine(string templateDirectory, bool cacheTemplate) : base(cacheTemplate)
		{
			this.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
			this.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDirectory);
			this.Init();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="templateName">Name of the template.</param>
		/// <returns></returns>
		public string Process(IDictionary context, string templateName)
		{
			StringWriter writer = new StringWriter();

			try
			{
				Template template = this.GetTemplate(templateName);
				template.Merge(CreateContext(context), writer);
			}
			catch (ResourceNotFoundException rnf)
			{
				return rnf.Message;
			}
			catch (ParseErrorException pe)
			{
				return pe.Message;
			}

			return writer.ToString();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="writer">The writer.</param>
		/// <param name="templateName">Name of the template.</param>
		public void Process(IDictionary context, TextWriter writer, string templateName)
		{
			try
			{
				Template template = this.GetTemplate(templateName);
				template.Merge(CreateContext(context), writer);
			}
			catch (ResourceNotFoundException rnf)
			{
				writer.Write(rnf.Message);
			}
			catch (ParseErrorException pe)
			{
				writer.Write(pe.Message);
			}
		}
	}
}
using System;
using System.Collections;
using System.IO;
using NVelocity.Context;
using NVelocity.Exception;
using NVelocityTemplateEngine.BaseClasses;
using NVelocityTemplateEngine.Interfaces;

namespace NVelocityTemplateEngine.Engines
{
	/// <summary>
	/// Summary description for NVelocityMemoryEngine.
	/// </summary>
	public sealed class NVelocityMemoryEngine : NVelocityEngineBase, INVelocityEngine
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="NVelocityMemoryEngine"/> class.
		/// </summary>
		/// <param name="cacheTamplate">if set to <c>true</c> [cache tamplate].</param>
		internal NVelocityMemoryEngine(bool cacheTamplate) : base(cacheTamplate)
		{
			this.Init();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="template">The template.</param>
		/// <returns></returns>
		public string Process(IDictionary context, string template)
		{
			StringWriter writer = new StringWriter();

			try
			{
				this.Evaluate(CreateContext(context), writer, "mystring", template);
			}
			catch (ParseErrorException pe)
			{
				return pe.Message;
			}
			catch (MethodInvocationException mi)
			{
				return mi.Message;
			}

			return writer.ToString();
		}

		/// <summary>
		/// Processes the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="writer">The writer.</param>
		/// <param name="template">The template.</param>
		public void Process(IDictionary context, TextWriter writer, string template)
		{
			try
			{
				this.Evaluate(CreateContext(context), writer, "mystring", template);
			}
			catch (ParseErrorException pe)
			{
				writer.Write(pe.Message);
			}
			catch (MethodInvocationException mi)
			{
				writer.Write(mi.Message);
			}
		}
	}
}