├── todo.txt ├── .travis.yml ├── data-structures-csharp ├── data-structures-csharp │ ├── bin │ │ └── Debug │ │ │ └── CodeContracts │ │ │ └── DataStructures.noReferenceAssembly │ ├── data-structures-csharp.suo │ ├── Rope │ │ ├── Rope.cs │ │ └── Node.cs │ ├── BPlusTree │ │ ├── Split.cs │ │ ├── INode.cs │ │ ├── BPlusTree.cs │ │ ├── LeafNode.cs │ │ └── IntermediateNode.cs │ ├── Hash │ │ └── DoubleHashedDictionary.cs │ ├── data-structures-csharp.sln.docstates.suo │ ├── RedBlackTree │ │ ├── NodeType.cs │ │ ├── NullNode.cs │ │ └── Node.cs │ ├── Trie │ │ ├── NullNode.cs │ │ └── Node.cs │ ├── QuadTree │ │ ├── NullChildren.cs │ │ ├── Point.cs │ │ ├── QuadTree.cs │ │ ├── Rectangle.cs │ │ ├── Children.cs │ │ └── Node.cs │ ├── RegionQuadTree │ │ ├── Point.cs │ │ ├── NullChildren.cs │ │ ├── RegionQuadTree.cs │ │ ├── Rectangle.cs │ │ ├── Children.cs │ │ └── Node.cs │ ├── BTree │ │ ├── Node.cs │ │ ├── Entry.cs │ │ └── BTree.cs │ ├── CompressedTrie │ │ ├── NullNode.cs │ │ └── CompressedTrie.cs │ ├── TransportList │ │ └── TransposeList.cs │ ├── Utils │ │ └── StringUtils.cs │ ├── data-structures-csharp.sln │ ├── SplayTree │ │ ├── SplayTree.cs │ │ └── Node.cs │ ├── DAWG │ │ ├── DirectedAcyclicWordGraph.cs │ │ ├── Edge.cs │ │ └── Node.cs │ ├── RootedTree │ │ ├── RootedTree.cs │ │ └── Node.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SkipList │ │ ├── SkipNode.cs │ │ └── NullSkipNode.cs │ ├── FrequencyList │ │ ├── Node.cs │ │ └── FrequencyList.cs │ ├── IntervalTree │ │ ├── Interval.cs │ │ ├── Node.cs │ │ └── IntervalTree.cs │ ├── ConcurrentAdjacencyList │ │ └── ConcurrentAdjacencyList.cs │ ├── TransposeList │ │ ├── Node.cs │ │ └── TransposeList.cs │ ├── Heap │ │ ├── Node.cs │ │ └── Heap.cs │ ├── BinomialHeap │ │ └── Node.cs │ ├── ConcurrentHashSet │ │ └── ConcurrentHashSet.cs │ ├── AvlTree │ │ └── Node.cs │ ├── HSBT │ │ ├── Node.cs │ │ └── HeapStructuredBinaryTree.cs │ ├── Queue │ │ └── Deque.cs │ ├── AdjacencyList │ │ ├── AdjacencyList.cs │ │ └── WeightedAdjacencyList.cs │ ├── List │ │ ├── SortedList.cs │ │ └── MoveToFrontList.cs │ ├── BinarySearchTree │ │ ├── BinarySearchTreeTranspose.cs │ │ └── Node.cs │ ├── BloomFilter │ │ └── BloomFilter.cs │ └── CircularBuffer │ │ └── CircularBuffer.cs ├── data-structures-csharp.v11.suo ├── data-structures-csharp.v12.suo ├── data-structures-csharpTests │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── List │ │ ├── SortedListTests.cs │ │ ├── MoveToFrontListTests.cs │ │ └── CircularQueueTests.cs │ ├── Queue │ │ └── DequeTests.cs │ ├── Heap │ │ └── HeapTests.cs │ ├── BinarySearchTree │ │ └── BinarySearchTreeTransposeTests.cs │ └── AdjacencyList │ │ └── AdjacencyListTests.cs └── data-structures-csharp.sln ├── .gitignore ├── .gitattributes ├── LICENSE └── README.md /todo.txt: -------------------------------------------------------------------------------- 1 | Judy Array 2 | disjoint set data structure 3 | dancing link (knuth) 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | solution: data-structures-csharp/data-structures-csharp.sln -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/bin/Debug/CodeContracts/DataStructures.noReferenceAssembly: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp.v11.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/riyadparvez/data-structures-csharp/HEAD/data-structures-csharp/data-structures-csharp.v11.suo -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp.v12.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/riyadparvez/data-structures-csharp/HEAD/data-structures-csharp/data-structures-csharp.v12.suo -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/data-structures-csharp.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/riyadparvez/data-structures-csharp/HEAD/data-structures-csharp/data-structures-csharp/data-structures-csharp.suo -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Rope/Rope.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.RopeSpace 4 | { 5 | [Serializable] 6 | public partial class Rope 7 | { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.dll 3 | /data-structures-csharp/data-structures-csharp/obj/* 4 | /data-structures-csharp/data-structures-csharp/obj/bin/* 5 | /data-structures-csharp/data-structures-test/obj/* 6 | /data-structures-csharp/data-structures-test/bin/* 7 | /data-structures-csharp/data-structures-test/TestResults/* 8 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BPlusTree/Split.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | 4 | namespace DataStructures.BPlusTreeSpace 5 | { 6 | public partial class BPlusTree 7 | where TKey : IComparable 8 | { 9 | internal class Split 10 | { 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Hash/DoubleHashedDictionary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace DataStructures.Hash 7 | { 8 | [Serializable] 9 | public class DoubleHashedDictionary 10 | { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/data-structures-csharp.sln.docstates.suo: -------------------------------------------------------------------------------- 1 | 2 | 3 |  -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RedBlackTree/NodeType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DataStructures.RedBlackTreeSpace 8 | { 9 | public partial class RedBlackTree 10 | { 11 | public enum NodeType 12 | { 13 | Red, 14 | Black, 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Rope/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace DataStructures.Rope 7 | { 8 | [Serializable] 9 | public partial class Rope 10 | { 11 | [Serializable] 12 | private class Node 13 | { 14 | public int Weight { get; set; } 15 | public Node Left { get; set; } 16 | public Node Right { get; set; } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Trie/NullNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | 5 | namespace DataStructures.TrieSpace 6 | { 7 | public partial class Trie : IEnumerable 8 | { 9 | [Serializable] 10 | private sealed class NullNode : Node 11 | { 12 | public NullNode(string wordFromRoot, Node parent) 13 | : base((char)0, wordFromRoot, parent) 14 | { 15 | 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BPlusTree/INode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | 4 | namespace DataStructures.BPlusTreeSpace 5 | { 6 | public partial class BPlusTree 7 | where TKey : IComparable 8 | { 9 | public interface INode 10 | where TKey : IComparable 11 | { 12 | int GetLocation(TKey key); 13 | // returns null if no split, otherwise returns split info 14 | //Split Insert(TKey key, TValue value); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/NullChildren.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.QuadTreeSpace 4 | { 5 | public partial class QuadTree 6 | { 7 | [Serializable] 8 | private sealed class NullChildren : Children 9 | { 10 | public NullChildren(Node parent) 11 | : base(parent, null, null, null, null) 12 | { 13 | 14 | } 15 | 16 | public override Node GetContainingChild(Point point) 17 | { 18 | return null; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/Point.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.QuadTreeSpace 4 | { 5 | [Serializable] 6 | public struct Point 7 | { 8 | private double x; 9 | private double y; 10 | 11 | public double X 12 | { 13 | get { return x; } 14 | set { x = value; } 15 | } 16 | public double Y 17 | { 18 | get { return y; } 19 | set { y = value; } 20 | } 21 | 22 | public Point(double x, double y) 23 | { 24 | this.x = x; 25 | this.y = y; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/Point.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.RegionQuadTreeSpace 4 | { 5 | [Serializable] 6 | public struct Point 7 | { 8 | private double x; 9 | private double y; 10 | 11 | public double X 12 | { 13 | get { return x; } 14 | set { x = value; } 15 | } 16 | public double Y 17 | { 18 | get { return y; } 19 | set { y = value; } 20 | } 21 | 22 | public Point(double x, double y) 23 | { 24 | this.x = x; 25 | this.y = y; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/NullChildren.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.RegionQuadTreeSpace 4 | { 5 | public partial class RegionQuadTree 6 | { 7 | [Serializable] 8 | private sealed class NullChildren : Children 9 | where T : IComparable, IEquatable 10 | { 11 | public NullChildren(Node parent) 12 | : base(parent, null, null, null, null) 13 | { 14 | 15 | } 16 | 17 | public override Node GetContainingChild(Point point) 18 | { 19 | return null; 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.BTreeSpace 4 | { 5 | public partial class BTree 6 | where TKey : IComparable 7 | { 8 | [Serializable] 9 | private sealed class Node 10 | where TKey : IComparable 11 | { 12 | internal int numberOfChildren; 13 | internal Entry[] Children { get; set; } 14 | 15 | public Node(int maximumNumberOfChildren) 16 | { 17 | this.numberOfChildren = maximumNumberOfChildren; 18 | Children = new Entry[maximumNumberOfChildren]; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/CompressedTrie/NullNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | 4 | namespace DataStructures.CompressedTrieSpace 5 | { 6 | public partial class CompressedTrie 7 | { 8 | /// 9 | /// Null object pattern for Node 10 | /// 11 | [Serializable] 12 | private sealed class NullNode : Node 13 | { 14 | public override string StringFragment 15 | { 16 | get 17 | { 18 | return string.Empty; 19 | } 20 | } 21 | 22 | public NullNode(string wordFromRoot) 23 | : base(wordFromRoot) 24 | { 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/TransportList/TransposeList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace DataStructures.TransposeListSpaceS 8 | { 9 | public class TransposeList : IEnumerable 10 | { 11 | private List list = new List(); 12 | 13 | T Get(T element) 14 | { 15 | 16 | } 17 | 18 | public IEnumerator GetEnumerator() 19 | { 20 | throw new NotImplementedException(); 21 | } 22 | 23 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 24 | { 25 | throw new NotImplementedException(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RedBlackTree/NullNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | 8 | namespace DataStructures.RedBlackTreeSpace 9 | { 10 | public partial class RedBlackTree 11 | { 12 | [Serializable] 13 | public sealed class NullNode : Node 14 | where TKey : IComparable 15 | { 16 | public NullNode() 17 | : base() 18 | { 19 | } 20 | public NullNode(TKey key) : base(key) 21 | { 22 | } 23 | 24 | public NullNode(TKey key, TValue value, Node left, Node right) : base(key, value, left, right) 25 | { 26 | } 27 | 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Utils/StringUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.Utils 6 | { 7 | public static class StringUtils 8 | { 9 | public static string CommonPrefix(this string str1, string str2) 10 | { 11 | Contract.Ensures(Contract.Result() != null); 12 | return str1.Substring(0, str1.CommonPrefixLength(str2)); 13 | } 14 | 15 | public static int CommonPrefixLength(this string str1, string str2) 16 | { 17 | Contract.Requires(str2 != null); 18 | Contract.Ensures(Contract.Result() >= 0); 19 | 20 | int count = 0; 21 | for (int i = 0; i < str1.Length && i < str2.Length; i++, count++) 22 | { 23 | if (str1[i] != str2[i]) 24 | { 25 | break; 26 | } 27 | } 28 | return count; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/data-structures-csharp.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "data-structures-csharp", "data-structures-csharp.csproj", "{4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/SplayTree/SplayTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.SplayTreeSpace 6 | { 7 | //TODO: Splay Tree 8 | /// 9 | /// Splay Tree upon access an element it makes that element root 10 | /// 11 | /// 12 | [Serializable] 13 | public partial class SplayTree 14 | where T : IComparable, IEquatable 15 | { 16 | public int Count { get; private set; } 17 | private Node root; 18 | 19 | public void Add(T data) 20 | { 21 | Contract.Requires(data != null); 22 | 23 | } 24 | 25 | public void Remove(T data) 26 | { 27 | Contract.Requires(data != null); 28 | } 29 | 30 | [Pure] 31 | public T Find(T data) 32 | { 33 | Contract.Requires(data != null); 34 | return default(T); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | Copyright (c) 2015 Riyad Parvez 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | The above copyright notice and this permission notice shall be 11 | included in all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 13 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 14 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 15 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 16 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 18 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BTree/Entry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DataStructures.BTreeSpace 4 | { 5 | public partial class BTree 6 | where TKey : IComparable 7 | { 8 | /// 9 | /// Every entry in children contains either a key value pair or link to next child 10 | /// internal nodes: only use key and next 11 | /// external nodes: only use key and value 12 | /// 13 | /// 14 | /// 15 | [Serializable] 16 | private sealed class Entry 17 | where TKey : IComparable 18 | { 19 | public TKey Key { get; set; } 20 | public TValue Value { get; set; } 21 | public Node ChildNode { get; set; } 22 | 23 | public Entry(TKey key, TValue value, Node next) 24 | { 25 | this.Key = key; 26 | this.Value = value; 27 | this.ChildNode = next; 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/DAWG/DirectedAcyclicWordGraph.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | //TODO: Add word 5 | namespace DataStructures.DAWGSpace 6 | { 7 | /// 8 | /// 9 | /// 10 | [Serializable] 11 | public partial class DirectedAcyclicWordGraph 12 | { 13 | private Node root; 14 | 15 | public void Add(string word) 16 | { 17 | Contract.Requires(!string.IsNullOrEmpty(word)); 18 | } 19 | 20 | /// 21 | /// Check if this word exists in this tree 22 | /// 23 | /// 24 | /// 25 | public bool Find(string word) 26 | { 27 | Contract.Requires(!string.IsNullOrEmpty(word)); 28 | 29 | var currentNode = root; 30 | foreach (var ch in word) 31 | { 32 | var e = currentNode.FindEdge(ch); 33 | if (e == null) 34 | { 35 | return false; 36 | } 37 | Contract.Assert(e.StartNode.Equals(currentNode)); 38 | currentNode = e.EndNode; 39 | } 40 | return true; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Data Structures C# 2 | ====================== 3 | 4 | [![HitCount](http://hits.dwyl.io/riyadparvez/riyadparvez/data-structures-csharp.svg)](http://hits.dwyl.io/riyadparvez/riyadparvez/data-structures-csharp) 5 | 6 | **Looking for maintainers** 7 | 8 | I don't have time to maintain this project anymore. If you are interested into maintaining this project, please drop me an email. 9 | 10 | ------------------------------------------------------------------------ 11 | A library for all the data structures in C#. Every class will be generic and reusable. It uses [http://research.microsoft.com/contracts](http://research.microsoft.com/contracts "Code Contract") library. 12 | 13 | **Caution:** This library is under development and not tested. Anything can break. 14 | 15 | Implemented data structures are: 16 | 17 | - AVL Tree 18 | - B+ Tree 19 | - Binary Search Tree 20 | - Binary Search Tree (Transpose) 21 | - Binomial Heap 22 | - Bloom Filter 23 | - Compressed Trie 24 | - Concurrent Hash Set 25 | - Directed Acyclic Word Graph 26 | - Heap 27 | - Heap Structured Binary Tree 28 | - Interval Tree 29 | - List (Move to front heuristics) 30 | - List (Frequency count heuristics) 31 | - List (Transpose heuristics) 32 | - Red Black Tree 33 | - Region Quad Tree 34 | - Rooted Tree 35 | - Splay Tree 36 | - Skip List 37 | - Trie 38 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RootedTree/RootedTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | 7 | namespace DataStructures.RootedTreeSpace 8 | { 9 | [Serializable] 10 | public partial class RootedTree 11 | where T : IComparable, IEquatable 12 | { 13 | private void PushLeft(Stack> stack, Node x) 14 | { 15 | Contract.Requires(stack != null); 16 | 17 | while (x != null) 18 | { 19 | stack.Push(x); 20 | x = x.Left; 21 | } 22 | } 23 | 24 | /// 25 | /// Merge two trees 26 | /// 27 | /// Returned merged tree node 28 | public Node Merge(Node root1, Node root2) 29 | { 30 | Contract.Requires(root1 != null); 31 | Contract.Requires(root2 != null); 32 | 33 | var stack = new Stack>(); 34 | PushLeft(stack, root2); 35 | while (stack.Any()) 36 | { 37 | var x = stack.Pop(); 38 | x.Root = root1.Root; 39 | PushLeft(stack, x.Right); 40 | } 41 | return root1.Root; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("data-structures-csharp")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("data-structures-csharp")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0f8e9ce5-3006-4b10-b98b-65e55aa15862")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("data-structures-csharpTests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("data-structures-csharpTests")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("dcaf6182-ac0d-4b9e-a18a-e4a522e76fde")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/SkipList/SkipNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | namespace DataStructures.SkipListSpace 6 | { 7 | public partial class SkipList : IEnumerable, ICollection 8 | where TKey : IComparable 9 | { 10 | [Serializable] 11 | private class SkipNode 12 | where TKey : IComparable 13 | { 14 | public TKey Key { get; set; } 15 | public TValue Value { get; set; } 16 | //Each link contains next level successor in skip list 17 | public IList> Links { get; private set; } 18 | 19 | [ContractInvariantMethod] 20 | private void ObjectInvariant() 21 | { 22 | Contract.Invariant(Links != null); 23 | Contract.Invariant(Links.Count > 0); 24 | } 25 | 26 | public SkipNode(int level) 27 | { 28 | Contract.Requires(level > 0); 29 | Links = new List>(level); 30 | } 31 | 32 | public SkipNode(int level, TKey key, TValue value) 33 | { 34 | Contract.Requires(key != null); 35 | Contract.Requires(level > 0); 36 | 37 | Key = key; 38 | Value = value; 39 | Links = new List>(level); 40 | } 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/FrequencyList/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | namespace DataStructures.FrequencyListSpace 5 | { 6 | public partial class FrequencyList 7 | { 8 | [Serializable] 9 | public class Node 10 | where T : IComparable 11 | { 12 | public int AccessCount { get; set; } 13 | public T Value { get; set; } 14 | public Node Previous { get; set; } 15 | public Node Next { get; set; } 16 | 17 | [ContractInvariantMethod] 18 | private void ObjectInvariant() 19 | { 20 | Contract.Invariant(AccessCount >= 0); 21 | } 22 | 23 | public Node() 24 | { 25 | } 26 | 27 | public Node(T data) 28 | { 29 | Contract.Requires(data != null); 30 | Value = data; 31 | } 32 | 33 | public override int GetHashCode() 34 | { 35 | unchecked 36 | { 37 | int hash = 17; 38 | hash = 23 * Value.GetHashCode(); 39 | return hash; 40 | } 41 | } 42 | 43 | public override bool Equals(object obj) 44 | { 45 | Node otherObject = obj as Node; 46 | if (otherObject == null) 47 | { 48 | return false; 49 | } 50 | return Value.Equals(otherObject.Value); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/QuadTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.QuadTreeSpace 6 | { 7 | [Serializable] 8 | public partial class QuadTree 9 | { 10 | public readonly int MaximumElementsPerNode; 11 | private readonly Rectangle region; 12 | private readonly Node root; 13 | 14 | public Rectangle Region 15 | { 16 | get { return region; } 17 | } 18 | 19 | [ContractInvariantMethod] 20 | private void ObjectInvariant() 21 | { 22 | Contract.Invariant(MaximumElementsPerNode > 0); 23 | } 24 | 25 | public QuadTree(int maximumElementsPerNode, Rectangle region) 26 | { 27 | Contract.Requires(maximumElementsPerNode > 0); 28 | 29 | MaximumElementsPerNode = maximumElementsPerNode; 30 | this.region = region; 31 | root = new Node(region, null, maximumElementsPerNode); 32 | } 33 | 34 | public bool Add(Point point, T element) 35 | { 36 | Contract.Requires(element != null); 37 | 38 | var current = root; 39 | while (current.IsInRegion(point)) 40 | { 41 | var node = current.GetContainingChild(point); 42 | if (node == null) 43 | { 44 | node.Add(point, element); 45 | } 46 | else 47 | { 48 | current = node; 49 | } 50 | } 51 | return false; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "data-structures-csharp", "data-structures-csharp\data-structures-csharp.csproj", "{4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}" 5 | EndProject 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{766A7C32-1293-4288-9E64-1C4BF82ABCDF}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "data-structures-csharpTests", "data-structures-csharpTests\data-structures-csharpTests.csproj", "{9D516B73-8B54-434A-84BE-AE95803720C5}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {4FBD79E3-616A-4F3E-B2CA-65FED347C8E3}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {9D516B73-8B54-434A-84BE-AE95803720C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {9D516B73-8B54-434A-84BE-AE95803720C5}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {9D516B73-8B54-434A-84BE-AE95803720C5}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {9D516B73-8B54-434A-84BE-AE95803720C5}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/SkipList/NullSkipNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace DataStructures.SkipListSpace 5 | { 6 | public partial class SkipList : IEnumerable, ICollection 7 | where TKey : IComparable 8 | { 9 | [Serializable] 10 | private sealed class NullSkipNode : SkipNode 11 | where TKey : IComparable 12 | { 13 | public NullSkipNode(int level) 14 | : base(level) 15 | { 16 | 17 | } 18 | 19 | public bool Equals(SkipNode otherNode) 20 | { 21 | NullSkipNode otherNullNode = otherNode as NullSkipNode; 22 | if (otherNullNode == null) 23 | { 24 | return false; 25 | } 26 | return true; 27 | } 28 | } 29 | 30 | public void Add(TValue item) 31 | { 32 | throw new NotImplementedException(); 33 | } 34 | 35 | public void Clear() 36 | { 37 | throw new NotImplementedException(); 38 | } 39 | 40 | public bool Contains(TValue item) 41 | { 42 | throw new NotImplementedException(); 43 | } 44 | 45 | public void CopyTo(TValue[] array, int arrayIndex) 46 | { 47 | throw new NotImplementedException(); 48 | } 49 | 50 | public bool Remove(TValue item) 51 | { 52 | throw new NotImplementedException(); 53 | } 54 | 55 | public bool IsReadOnly { get; private set; } 56 | } 57 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/IntervalTree/Interval.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | 6 | namespace DataStructures.IntervalTreeSpace 7 | { 8 | [Serializable] 9 | public struct Interval : IEquatable 10 | { 11 | private double start; 12 | private double end; 13 | public double Start 14 | { 15 | get { return start; } 16 | set { start = value; } 17 | } 18 | public double End 19 | { 20 | get { return end; } 21 | set { end = value; } 22 | } 23 | public double Median 24 | { 25 | get { return (start + end) / 2; } 26 | } 27 | 28 | [ContractInvariantMethod] 29 | private void StructInvariant() 30 | { 31 | Contract.Invariant(start <= end); 32 | } 33 | 34 | public Interval(double start, double end) 35 | { 36 | this.start = start; 37 | this.end = end; 38 | } 39 | 40 | public bool Equals(Interval otherInterval) 41 | { 42 | return start.Equals(otherInterval.Start) && 43 | end.Equals(otherInterval.End); 44 | } 45 | } 46 | 47 | public class StartComparer : Comparer 48 | { 49 | public override int Compare(Interval x, Interval y) 50 | { 51 | return x.Start.CompareTo(y.Start); 52 | } 53 | } 54 | 55 | public class EndComparer : Comparer 56 | { 57 | public override int Compare(Interval x, Interval y) 58 | { 59 | return x.End.CompareTo(y.End); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RedBlackTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | namespace DataStructures.RedBlackTreeSpace 5 | { 6 | public partial class RedBlackTree 7 | { 8 | [Serializable] 9 | public class Node 10 | where TKey : IComparable 11 | { 12 | public TKey Key { get; set; } 13 | public TValue Value { get; set; } 14 | public NodeType Color { get; set; } 15 | public Node Left { get; set; } 16 | public Node Right { get; set; } 17 | 18 | public Node() 19 | { 20 | Color = NodeType.Black; 21 | Key = default(TKey); 22 | Left = null; 23 | Right = null; 24 | } 25 | 26 | public Node(TKey key) 27 | { 28 | Color = NodeType.Black; 29 | Key = key; 30 | Left = null; 31 | Right = null; 32 | } 33 | 34 | public Node(TKey key, TValue value, Node left, Node right) 35 | { 36 | Contract.Requires(key != null); 37 | 38 | Key = key; 39 | Value = value; 40 | Left = left; 41 | Right = right; 42 | } 43 | 44 | //public Node(TKey key, TValue value, Node left, Node right) 45 | //{ 46 | // Key = key; 47 | // Value = value; 48 | // Left = left; 49 | // Right = right; 50 | //} 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/RegionQuadTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.RegionQuadTreeSpace 6 | { 7 | [Serializable] 8 | public partial class RegionQuadTree 9 | where T : IComparable, IEquatable 10 | { 11 | private readonly Rectangle region; 12 | private readonly Node root; 13 | 14 | public Rectangle Region 15 | { 16 | get { return region; } 17 | } 18 | 19 | public RegionQuadTree(Rectangle region) 20 | { 21 | this.region = region; 22 | root = new Node(region, default(T), null); 23 | } 24 | 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | public bool SetData(Point point, T data) 32 | { 33 | Contract.Requires(data != null); 34 | 35 | var current = root; 36 | while (true) 37 | { 38 | if (!current.IsInRegion(point)) 39 | { 40 | return false; 41 | } 42 | else 43 | { 44 | Node node = current.GetContainingChild(point); 45 | if (node != null) 46 | { 47 | current = node; 48 | } 49 | else 50 | { 51 | break; 52 | } 53 | } 54 | } 55 | current.SetData(point, data); 56 | return true; 57 | } 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/Rectangle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.QuadTreeSpace 6 | { 7 | [Serializable] 8 | public struct Rectangle 9 | { 10 | private Point topLeftPoint; 11 | private double width; 12 | private double height; 13 | 14 | public Point TopLeftPoint 15 | { 16 | get { return topLeftPoint; } 17 | } 18 | public double Width 19 | { 20 | get { return width; } 21 | } 22 | public double Height 23 | { 24 | get { return height; } 25 | } 26 | 27 | public Rectangle(Point topLeftPoint, double width, double height) 28 | { 29 | Contract.Requires(width > 0); 30 | Contract.Requires(height > 0); 31 | 32 | this.topLeftPoint = topLeftPoint; 33 | this.width = width; 34 | this.height = height; 35 | } 36 | 37 | public bool Intersects(Rectangle rectangle) 38 | { 39 | return IsInRectangle(rectangle.TopLeftPoint) || 40 | rectangle.IsInRectangle(this.TopLeftPoint); 41 | } 42 | 43 | public bool Contains(Rectangle rectangle) 44 | { 45 | return IsInRectangle(rectangle.TopLeftPoint) && 46 | IsInRectangle(new Point(rectangle.TopLeftPoint.X + Width, rectangle.TopLeftPoint.Y + Height)); 47 | } 48 | 49 | public bool IsInRectangle(Point point) 50 | { 51 | return (point.X >= TopLeftPoint.X) && 52 | (point.X <= (TopLeftPoint.X + Width)) && 53 | (point.Y >= TopLeftPoint.Y) && 54 | (point.Y >= (TopLeftPoint.Y + Height)); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/Rectangle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.RegionQuadTreeSpace 6 | { 7 | [Serializable] 8 | public struct Rectangle 9 | { 10 | private Point topLeftPoint; 11 | private double width; 12 | private double height; 13 | 14 | public Point TopLeftPoint 15 | { 16 | get { return topLeftPoint; } 17 | } 18 | public double Width 19 | { 20 | get { return width; } 21 | } 22 | public double Height 23 | { 24 | get { return height; } 25 | } 26 | 27 | public Rectangle(Point topLeftPoint, double width, double height) 28 | { 29 | Contract.Requires(width > 0); 30 | Contract.Requires(height > 0); 31 | 32 | this.topLeftPoint = topLeftPoint; 33 | this.width = width; 34 | this.height = height; 35 | } 36 | 37 | public bool Intersects(Rectangle rectangle) 38 | { 39 | return IsInRectangle(rectangle.TopLeftPoint) || 40 | rectangle.IsInRectangle(this.TopLeftPoint); 41 | } 42 | 43 | public bool Contains(Rectangle rectangle) 44 | { 45 | return IsInRectangle(rectangle.TopLeftPoint) && 46 | IsInRectangle(new Point(rectangle.TopLeftPoint.X + Width, rectangle.TopLeftPoint.Y + Height)); 47 | } 48 | 49 | public bool IsInRectangle(Point point) 50 | { 51 | return (point.X >= TopLeftPoint.X) && 52 | (point.X <= (TopLeftPoint.X + Width)) && 53 | (point.Y >= TopLeftPoint.Y) && 54 | (point.Y >= (TopLeftPoint.Y + Height)); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/ConcurrentAdjacencyList/ConcurrentAdjacencyList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.Contracts; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace DataStructures.ConcurrentAdjacencyList 9 | { 10 | //TODO: incomplete, requires inspection 11 | [Serializable] 12 | public class ConcurrentAdjacencyList 13 | { 14 | private readonly ConcurrentDictionary> dict = new ConcurrentDictionary>(); 15 | 16 | public IList Vertices 17 | { 18 | get { return dict.Keys.ToList(); } 19 | } 20 | 21 | public int Count 22 | { 23 | get { return dict.Count; } 24 | } 25 | 26 | public void AddVertex(T vertex) 27 | { 28 | Contract.Requires(vertex != null); 29 | dict[vertex] = new List(); 30 | } 31 | 32 | public void AddEdge(T vertex1, T vertex2) 33 | { 34 | Contract.Requires(vertex1 != null); 35 | Contract.Requires(vertex2 != null); 36 | dict[vertex1].Add(vertex2); 37 | dict[vertex2].Add(vertex1); 38 | } 39 | 40 | public bool IsNeighbourOf(T vertex, T neighbour) 41 | { 42 | Contract.Requires(vertex != null); 43 | Contract.Requires(neighbour != null); 44 | return dict.ContainsKey(vertex) && dict[vertex].Contains(neighbour); 45 | } 46 | 47 | public IList GetNeighbours(T vertex) 48 | { 49 | Contract.Requires(vertex != null); 50 | return dict.ContainsKey(vertex)? dict[vertex]: new List(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BPlusTree/BPlusTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BPlusTreeSpace 6 | { 7 | [Serializable] 8 | public partial class BPlusTree 9 | where TKey : IComparable 10 | { 11 | private INode root; 12 | /// 13 | /// the maximum number of key value pairs in the leaf node, M must be > 0 14 | /// 15 | public readonly int NumberOfValuesInLeafNode; 16 | /// 17 | /// the maximum number of keys in inner node, the number of pointer is N+1, N must be > 2 18 | /// 19 | public readonly int NumberOfKeysInIntermediateNode; 20 | 21 | [ContractInvariantMethod] 22 | private void ObjectInvariant() 23 | { 24 | Contract.Invariant(NumberOfValuesInLeafNode > 0); 25 | Contract.Invariant(NumberOfKeysInIntermediateNode > 2); 26 | } 27 | 28 | public BPlusTree(int m, int n) 29 | { 30 | Contract.Requires(m > 0); 31 | Contract.Requires(n > 2); 32 | 33 | NumberOfValuesInLeafNode = m; 34 | NumberOfKeysInIntermediateNode = n; 35 | } 36 | 37 | private bool Find(TKey key, INode node) 38 | { 39 | Contract.Requires(key != null); 40 | Contract.Requires(node != null); 41 | 42 | if (node is LeafNode) 43 | { 44 | } 45 | return false; 46 | } 47 | 48 | [Pure] 49 | public bool Find(TKey key) 50 | { 51 | Contract.Requires(key != null); 52 | return Find(key, root); 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/DAWG/Edge.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.DAWGSpace 6 | { 7 | public partial class DirectedAcyclicWordGraph 8 | { 9 | /// 10 | /// Every edge corresponds to different edge between two nodes of graph 11 | /// 12 | [Serializable] 13 | private class Edge 14 | { 15 | private readonly char ch; 16 | 17 | public char Char { get { return ch; } } 18 | public Node StartNode { get; private set; } 19 | public Node EndNode { get; private set; } 20 | 21 | public Edge(char character, Node startNode, Node endNode) 22 | { 23 | Contract.Requires(startNode != null); 24 | Contract.Requires(endNode != null); 25 | 26 | ch = character; 27 | StartNode = startNode; 28 | EndNode = endNode; 29 | } 30 | 31 | public override bool Equals(object obj) 32 | { 33 | var otherEdge = obj as Edge; 34 | if (otherEdge == null) 35 | { 36 | return false; 37 | } 38 | return ch.Equals(otherEdge.ch) && 39 | StartNode.Equals(otherEdge.StartNode) && 40 | EndNode.Equals(otherEdge.EndNode); 41 | } 42 | 43 | public override int GetHashCode() 44 | { 45 | unchecked 46 | { 47 | int hash = 17; 48 | hash = 23 * ch.GetHashCode() + hash; 49 | hash = 23 * StartNode.GetHashCode() + hash; 50 | hash = 23 * EndNode.GetHashCode() + hash; 51 | return hash; 52 | } 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BPlusTree/LeafNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BPlusTreeSpace 6 | { 7 | public partial class BPlusTree 8 | where TKey : IComparable 9 | { 10 | [Serializable] 11 | private class LeafNode : INode 12 | where TKey : IComparable 13 | { 14 | private readonly TValue[] _values; 15 | private readonly int _numberOfValues; 16 | 17 | public LeafNode(int numberOfValues) 18 | { 19 | Contract.Requires(numberOfValues > 0); 20 | _numberOfValues = numberOfValues; 21 | _values = new TValue[numberOfValues]; 22 | } 23 | 24 | private int GetChildIndex(TKey key) 25 | { 26 | Contract.Requires(key != null); 27 | Contract.Ensures(Contract.Result() >= 0); 28 | Contract.Ensures(Contract.Result() <= _numberOfValues); 29 | 30 | // Simple linear search. Faster for small values of N or M, binary search would be faster for larger M / N 31 | for (int i = 0; i < _numberOfValues; i++) 32 | { 33 | if (_values[i].Equals(key)) 34 | { 35 | return i; 36 | } 37 | } 38 | return _numberOfValues; 39 | } 40 | 41 | public TValue GetChild(TKey key) 42 | { 43 | Contract.Requires(key != null); 44 | return _values[GetChildIndex(key)]; 45 | } 46 | 47 | public int GetLocation(TKey key) 48 | { 49 | throw new NotImplementedException(); 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BPlusTree/IntermediateNode.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BPlusTreeSpace 6 | { 7 | public partial class BPlusTree 8 | where TKey : IComparable 9 | { 10 | [Serializable] 11 | private class IntermediateNode : INode 12 | where TKey : IComparable 13 | { 14 | private readonly int numberOfChildren; 15 | private readonly TKey[] keys; 16 | private readonly INode[] children; 17 | 18 | 19 | public IntermediateNode(int numberOfChildren) 20 | { 21 | Contract.Requires(numberOfChildren > 2); 22 | 23 | keys = new TKey[numberOfChildren - 1]; 24 | children = new INode[numberOfChildren]; 25 | } 26 | 27 | //private int GetIndex(TKey key) 28 | //{ 29 | // // Simple linear search. Faster for small values of N or M 30 | // for (int i = 0; i < num; i++) 31 | // { 32 | // if (keys[i].CompareTo(key) > 0) 33 | // { 34 | // return i; 35 | // } 36 | // } 37 | // return num; 38 | //} 39 | 40 | //public INode 41 | 42 | public int GetLocation(TKey key) 43 | { 44 | const int errorNum = -1; 45 | // Simple linear search. Faster for small values of N or M 46 | for (int i = 0; i < keys.Length; i++) 47 | { 48 | if (keys[i].CompareTo(key) > 0) 49 | { 50 | return i; 51 | } 52 | } 53 | return errorNum; 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/DAWG/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | 7 | namespace DataStructures.DAWGSpace 8 | { 9 | public partial class DirectedAcyclicWordGraph 10 | { 11 | [Serializable] 12 | private class Node 13 | { 14 | public List edges = new List(); 15 | public Guid Id { get; private set; } 16 | 17 | private Node(Guid id) 18 | { 19 | Id = id; 20 | } 21 | 22 | public void AddEdge(Edge e) 23 | { 24 | //Edge should have this node as one of the end nodes 25 | Contract.Requires(e.StartNode.Equals(this) || 26 | e.EndNode.Equals(this)); 27 | edges.Add(e); 28 | } 29 | 30 | /// 31 | /// 32 | /// 33 | /// 34 | /// Null if there is no such edge 35 | public Edge FindEdge(char ch) 36 | { 37 | return edges.SingleOrDefault(e => e.Char.Equals(ch)); 38 | } 39 | 40 | public override bool Equals(object obj) 41 | { 42 | var otherNode = obj as Node; 43 | if (otherNode == null) 44 | { 45 | return false; 46 | } 47 | return Id.Equals(otherNode.Id); 48 | } 49 | 50 | public override int GetHashCode() 51 | { 52 | unchecked 53 | { 54 | int hash = 17; 55 | hash = 23 * Id.GetHashCode() + hash; 56 | return hash; 57 | } 58 | } 59 | 60 | private static class Builder 61 | { 62 | public static Node CreateInstance() 63 | { 64 | return new Node(Guid.NewGuid()); 65 | } 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/TransposeList/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace DataStructures.TransposeListSpace 9 | { 10 | public partial class TransposeList 11 | { 12 | [Serializable] 13 | private class Node : IEquatable 14 | { 15 | public T Data { get; set; } 16 | public Node Previous { get; set; } 17 | public Node Next { get; set; } 18 | 19 | public Node() 20 | { 21 | } 22 | 23 | public Node(T data) 24 | { 25 | Data = data; 26 | } 27 | 28 | public override int GetHashCode() 29 | { 30 | unchecked 31 | { 32 | int hash = 17; 33 | hash = 23 * Data.GetHashCode(); 34 | return hash; 35 | } 36 | } 37 | 38 | public bool Equals(Node otherNode) 39 | { 40 | if (otherNode == null) 41 | { 42 | return false; 43 | } 44 | return Data.Equals(otherNode.Data); 45 | } 46 | 47 | public override bool Equals(object obj) 48 | { 49 | Node otherObject = obj as Node; 50 | if(otherObject == null) 51 | { 52 | return false; 53 | } 54 | return Data.Equals(otherObject.Data); 55 | } 56 | 57 | public bool Equals(T other) 58 | { 59 | if (other == null) 60 | { 61 | return false; 62 | } 63 | return Data.Equals(other); 64 | } 65 | 66 | //public bool Remove(T key) 67 | //{ 68 | // Contract.Requires(key != null, "key"); 69 | // Previous.Next = Next; 70 | // Next.Previous = Previous; 71 | // Data = default(T); 72 | // return true; 73 | //} 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/SplayTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | namespace DataStructures.SplayTreeSpace 5 | { 6 | public partial class SplayTree 7 | { 8 | /// 9 | /// Node of BST, left 11 | /// Data type 12 | [Serializable] 13 | private class Node 14 | where T : IComparable, IEquatable 15 | { 16 | public readonly T data; 17 | 18 | public T Data 19 | { 20 | get { return data; } 21 | } 22 | public int Height { get; set; } 23 | public Node Parent { get; set; } 24 | public Node Left { get; set; } 25 | public Node Right { get; set; } 26 | 27 | [ContractInvariantMethod] 28 | private void ObjectInvariant() 29 | { 30 | Contract.Invariant(Height >= 0); 31 | } 32 | 33 | public Node(T data, Node parent) 34 | { 35 | Contract.Requires(data != null); 36 | 37 | this.data = data; 38 | Parent = parent; 39 | Left = null; 40 | Right = null; 41 | } 42 | 43 | public bool Equals(Node otherNode) 44 | { 45 | if (otherNode == null) 46 | { 47 | return false; 48 | } 49 | return data.Equals(otherNode.Data); 50 | } 51 | 52 | public override bool Equals(object obj) 53 | { 54 | Node otherNode = obj as Node; 55 | if (otherNode == null) 56 | { 57 | return false; 58 | } 59 | return Data.Equals(otherNode.Data); 60 | } 61 | 62 | public override int GetHashCode() 63 | { 64 | unchecked // Overflow is fine, just wrap 65 | { 66 | int hash = 17; 67 | // Suitable nullity checks etc, of course :) 68 | hash = hash * 23 + data.GetHashCode(); 69 | return hash; 70 | } 71 | } 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RootedTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | namespace DataStructures.RootedTreeSpace 5 | { 6 | public partial class RootedTree 7 | { 8 | /// 9 | /// Node of rooted tree 10 | /// 11 | /// Data type 12 | [Serializable] 13 | public class Node 14 | where T : IComparable 15 | { 16 | public readonly T data; 17 | 18 | public T Data 19 | { 20 | get { return data; } 21 | } 22 | public int Height { get; set; } 23 | public Node Parent { get; set; } 24 | public Node Left { get; set; } 25 | public Node Right { get; set; } 26 | 27 | public Node Root { get; set; } 28 | 29 | [ContractInvariantMethod] 30 | private void ObjectInvariant() 31 | { 32 | Contract.Invariant(Root != null); 33 | } 34 | 35 | public Node(T data, Node parent) 36 | { 37 | Contract.Requires(parent != null); 38 | 39 | this.data = data; 40 | Parent = parent; 41 | Left = null; 42 | Right = null; 43 | } 44 | 45 | public bool Equals(Node otherNode) 46 | { 47 | if (otherNode == null) 48 | { 49 | return false; 50 | } 51 | return data.Equals(otherNode.Data); 52 | } 53 | 54 | public override bool Equals(object obj) 55 | { 56 | var otherNode = obj as Node; 57 | if (otherNode == null) 58 | { 59 | return false; 60 | } 61 | return Data.Equals(otherNode.Data); 62 | } 63 | 64 | public override int GetHashCode() 65 | { 66 | unchecked // Overflow is fine, just wrap 67 | { 68 | int hash = 17; 69 | // Suitable nullity checks etc, of course :) 70 | hash = hash * 23 + data.GetHashCode(); 71 | return hash; 72 | } 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Heap/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.HeapSpace 6 | { 7 | public partial class Heap 8 | { 9 | /// 10 | /// Node of Heap 11 | /// 12 | /// Data type 13 | [Serializable] 14 | private class Node 15 | where T : IComparable 16 | { 17 | private T val; 18 | 19 | public T Value 20 | { 21 | get 22 | { 23 | return val; 24 | } 25 | set 26 | { 27 | Contract.Requires(value != null); 28 | 29 | val = value; 30 | } 31 | } 32 | public int Height { get; set; } 33 | public Node Parent { get; set; } 34 | public Node Left { get; set; } 35 | public Node Right { get; set; } 36 | 37 | public Node(T val, Node parent) 38 | { 39 | Contract.Requires(val != null); 40 | 41 | this.val = val; 42 | Parent = parent; 43 | Left = null; 44 | Right = null; 45 | } 46 | 47 | public bool Equals(Node otherNode) 48 | { 49 | if (otherNode == null) 50 | { 51 | return false; 52 | } 53 | return val.Equals(otherNode.Value); 54 | } 55 | 56 | public override bool Equals(object obj) 57 | { 58 | Node otherNode = obj as Node; 59 | if (otherNode == null) 60 | { 61 | return false; 62 | } 63 | return val.Equals(otherNode.Value); 64 | } 65 | 66 | public override int GetHashCode() 67 | { 68 | unchecked // Overflow is fine, just wrap 69 | { 70 | int hash = 17; 71 | // Suitable nullity checks etc, of course :) 72 | hash = hash * 23 + val.GetHashCode(); 73 | return hash; 74 | } 75 | } 76 | } 77 | } 78 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BinomialHeap/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BinomialHeapSpace 6 | { 7 | public partial class BinomialHeap 8 | where T : IComparable 9 | { 10 | /// 11 | /// Node of Heap 12 | /// 13 | /// Data type 14 | [Serializable] 15 | private class Node 16 | where T : IComparable 17 | { 18 | private T val; 19 | 20 | public T Value 21 | { 22 | get { return val; } 23 | internal set 24 | { 25 | Contract.Requires(value != null); 26 | val = value; 27 | } 28 | } 29 | public int Degree { get; internal set; } 30 | internal Node Parent { get; set; } 31 | internal Node LeftChild { get; set; } 32 | internal Node RightSibling { get; set; } 33 | 34 | public Node(T val, Node parent, Node leftChild, Node rightSibling) 35 | { 36 | Contract.Requires(val != null); 37 | 38 | this.val = val; 39 | Parent = parent; 40 | LeftChild = null; 41 | RightSibling = null; 42 | } 43 | 44 | public Node(T val, Node parent) 45 | : this(val, parent, null, null) 46 | { 47 | } 48 | 49 | public bool Equals(Node otherNode) 50 | { 51 | if (otherNode == null) 52 | { 53 | return false; 54 | } 55 | return val.Equals(otherNode.Value); 56 | } 57 | 58 | public override bool Equals(object obj) 59 | { 60 | Node otherNode = obj as Node; 61 | if (otherNode == null) 62 | { 63 | return false; 64 | } 65 | return val.Equals(otherNode.Value); 66 | } 67 | 68 | public override int GetHashCode() 69 | { 70 | unchecked // Overflow is fine, just wrap 71 | { 72 | int hash = 17; 73 | // Suitable nullity checks etc, of course :) 74 | hash = hash * 23 + val.GetHashCode(); 75 | return hash; 76 | } 77 | } 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/CompressedTrie/CompressedTrie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.CompressedTrieSpace 6 | { 7 | /// 8 | /// Compressed trie which saves node space by compressing non branching 9 | /// nodes into one node 10 | /// 11 | [Serializable] 12 | public partial class CompressedTrie 13 | { 14 | private readonly Node root; 15 | 16 | [ContractInvariantMethod] 17 | private void ObjectInvariant() 18 | { 19 | Contract.Invariant(root != null); 20 | } 21 | 22 | public CompressedTrie() 23 | { 24 | root = new NullNode(string.Empty); 25 | } 26 | 27 | 28 | /// 29 | /// Check if an word exists 30 | /// 31 | /// word to search for 32 | /// True if that word exists 33 | [Pure] 34 | public bool Exists(string word) 35 | { 36 | Contract.Requires(!string.IsNullOrEmpty(word), "Trie doesn't include empty string or null values"); 37 | 38 | Node current = root; 39 | int count = 0; 40 | for (int i = 0; i < word.Length; i++, count++) 41 | { 42 | if (current.MoveToChildren(word.Substring(i))) 43 | { 44 | current = current.GetChild(word.Substring(i)); 45 | } 46 | else 47 | { 48 | break; 49 | } 50 | } 51 | return (count == word.Length); 52 | } 53 | 54 | /// 55 | /// Adds a word if it doesn't exist 56 | /// 57 | /// 58 | public void Add(string word) 59 | { 60 | Contract.Requires(!string.IsNullOrEmpty(word), "Trie doesn't include empty string or null values"); 61 | 62 | Node current = root; 63 | int count = 0; 64 | for (int i = 0; i < word.Length; i++, count++) 65 | { 66 | if (current.MoveToChildren(word.Substring(i))) 67 | { 68 | current = current.GetChild(word.Substring(i)); 69 | } 70 | else 71 | { 72 | current.AddChild(word.Substring(i)); 73 | } 74 | } 75 | 76 | if (count == word.Length) 77 | { 78 | //New word ends in this node 79 | current.AddNullNode(); 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/ConcurrentHashSet/ConcurrentHashSet.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | 5 | namespace DataStructures.ConcurrentHashSet 6 | { 7 | [Serializable] 8 | public class ConcurrentHashSet 9 | { 10 | private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); 11 | private readonly HashSet _hashSet = new HashSet(); 12 | 13 | //TODO: implement icollection 14 | public bool Add(T item) 15 | { 16 | try 17 | { 18 | _lock.EnterWriteLock(); 19 | return _hashSet.Add(item); 20 | } 21 | finally 22 | { 23 | if (_lock.IsWriteLockHeld) 24 | { 25 | _lock.ExitWriteLock(); 26 | } 27 | } 28 | } 29 | 30 | public void Clear() 31 | { 32 | try 33 | { 34 | _lock.EnterWriteLock(); 35 | _hashSet.Clear(); 36 | } 37 | finally 38 | { 39 | if (_lock.IsWriteLockHeld) 40 | { 41 | _lock.ExitWriteLock(); 42 | } 43 | } 44 | } 45 | 46 | public bool Contains(T item) 47 | { 48 | try 49 | { 50 | _lock.EnterReadLock(); 51 | return _hashSet.Contains(item); 52 | } 53 | finally 54 | { 55 | if (_lock.IsReadLockHeld) 56 | { 57 | _lock.ExitReadLock(); 58 | } 59 | } 60 | } 61 | 62 | public bool Remove(T item) 63 | { 64 | try 65 | { 66 | _lock.EnterWriteLock(); 67 | return _hashSet.Remove(item); 68 | } 69 | finally 70 | { 71 | if (_lock.IsWriteLockHeld) 72 | { 73 | _lock.ExitWriteLock(); 74 | } 75 | } 76 | } 77 | 78 | public int Count 79 | { 80 | get 81 | { 82 | try 83 | { 84 | _lock.EnterReadLock(); 85 | return _hashSet.Count; 86 | } 87 | finally 88 | { 89 | if (_lock.IsReadLockHeld) 90 | { 91 | _lock.ExitReadLock(); 92 | } 93 | } 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/AvlTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | namespace DataStructures.AvlTreeSpace 6 | { 7 | public partial class AvlTree : IEnumerable> 8 | where TKey : IComparable 9 | { 10 | /// 11 | /// Node of Heap 12 | /// 13 | /// Data type 14 | [Serializable] 15 | protected class Node 16 | where TKey : IComparable 17 | { 18 | private TKey key; 19 | private TValue val; 20 | 21 | public TKey Key 22 | { 23 | get { return key; } 24 | set 25 | { 26 | Contract.Requires(value != null); 27 | key = value; 28 | } 29 | 30 | } 31 | public TValue Value 32 | { 33 | get { return val; } 34 | set 35 | { 36 | Contract.Requires(value != null); 37 | val = value; 38 | } 39 | } 40 | public int Height { get; set; } 41 | public Node Parent { get; set; } 42 | public Node Left { get; set; } 43 | public Node Right { get; set; } 44 | 45 | public Node(TKey key, TValue val, Node parent, int height) 46 | { 47 | Contract.Requires(key != null); 48 | Contract.Requires(val != null); 49 | 50 | this.val = val; 51 | Parent = parent; 52 | Height = height; 53 | Left = null; 54 | Right = null; 55 | } 56 | 57 | public bool Equals(Node otherNode) 58 | { 59 | if (otherNode == null) 60 | { 61 | return false; 62 | } 63 | return val.Equals(otherNode.Value); 64 | } 65 | 66 | public override bool Equals(object obj) 67 | { 68 | var otherNode = obj as Node; 69 | if (otherNode == null) 70 | { 71 | return false; 72 | } 73 | return val.Equals(otherNode.Value); 74 | } 75 | 76 | public override int GetHashCode() 77 | { 78 | unchecked // Overflow is fine, just wrap 79 | { 80 | int hash = 17; 81 | // Suitable nullity checks etc, of course :) 82 | hash = hash * 23 + key.GetHashCode(); 83 | return hash; 84 | } 85 | } 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/HSBT/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.HsbtSpace 6 | { 7 | public partial class HeapStructuredBinaryTree 8 | { 9 | /// 10 | /// Node of Heap 11 | /// 12 | /// Data type 13 | [Serializable] 14 | private class Node 15 | where TKey : IComparable, IEquatable 16 | { 17 | private TKey key; 18 | private TValue val; 19 | 20 | public TKey Key 21 | { 22 | get { return key; } 23 | set 24 | { 25 | Contract.Requires(value != null); 26 | 27 | key = value; 28 | } 29 | 30 | } 31 | public TValue Value 32 | { 33 | get { return val; } 34 | set 35 | { 36 | Contract.Requires(value != null); 37 | 38 | val = value; 39 | } 40 | } 41 | public int Height { get; set; } 42 | public Node Parent { get; set; } 43 | public Node Left { get; set; } 44 | public Node Right { get; set; } 45 | 46 | public Node(TKey key, TValue val, Node parent) 47 | { 48 | Contract.Requires(key != null); 49 | Contract.Requires(val != null); 50 | 51 | this.val = val; 52 | Parent = parent; 53 | Left = null; 54 | Right = null; 55 | if (Parent != null) 56 | { 57 | Height = Parent.Height + 1; 58 | } 59 | } 60 | 61 | public bool Equals(Node otherNode) 62 | { 63 | if (otherNode == null) 64 | { 65 | return false; 66 | } 67 | return val.Equals(otherNode.Value); 68 | } 69 | 70 | public override bool Equals(object obj) 71 | { 72 | Node otherNode = obj as Node; 73 | if (otherNode == null) 74 | { 75 | return false; 76 | } 77 | return val.Equals(otherNode.Value); 78 | } 79 | 80 | public override int GetHashCode() 81 | { 82 | unchecked // Overflow is fine, just wrap 83 | { 84 | int hash = 17; 85 | // Suitable nullity checks etc, of course :) 86 | hash = hash * 23 + key.GetHashCode(); 87 | return hash; 88 | } 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Queue/Deque.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | 7 | namespace DataStructures.QueueSpace 8 | { 9 | /// 10 | /// 11 | /// 12 | /// 13 | [Serializable] 14 | public class Deque : IEnumerable 15 | { 16 | private List internalList; 17 | 18 | public int Count { get { return internalList.Count; } } 19 | public int Capacity { get { return internalList.Capacity; } } 20 | public T PeekFirst 21 | { 22 | get 23 | { 24 | return !internalList.Any() ? default(T) : internalList[0]; 25 | } 26 | } 27 | public T PeekLast 28 | { 29 | get 30 | { 31 | return !internalList.Any() ? default(T) : internalList[internalList.Count - 1]; 32 | } 33 | } 34 | 35 | /// 36 | /// Creates a queue using default capacity 37 | /// 38 | public Deque() 39 | { 40 | internalList = new List(); 41 | } 42 | 43 | /// 44 | /// Creates a deque with default capacity 45 | /// 46 | /// Default capacity of deque 47 | public Deque(int capacity) 48 | { 49 | Contract.Requires(capacity > 0); 50 | 51 | internalList = new List(capacity); 52 | } 53 | 54 | public void AddFirst(T item) 55 | { 56 | Contract.Requires(item != null); 57 | 58 | internalList.Insert(0, item); 59 | } 60 | 61 | /// 62 | /// Adds an item to the last of deque 63 | /// 64 | /// 65 | public void AddLast(T item) 66 | { 67 | Contract.Requires(item != null); 68 | 69 | internalList.Add(item); 70 | } 71 | 72 | /// 73 | /// 74 | /// 75 | /// Returns null if list is empty 76 | public T RemoveFirst() 77 | { 78 | if (!internalList.Any()) 79 | { 80 | return default(T); 81 | } 82 | var element = internalList[0]; 83 | internalList.RemoveAt(0); 84 | return element; 85 | } 86 | 87 | /// 88 | /// 89 | /// 90 | /// Returns null if list is empty 91 | public T RemoveLast() 92 | { 93 | if (!internalList.Any()) 94 | { 95 | return default(T); 96 | } 97 | var element = internalList[Count - 1]; 98 | internalList.RemoveAt(Count - 1); 99 | return element; 100 | } 101 | 102 | public IEnumerator GetEnumerator() 103 | { 104 | return internalList.GetEnumerator(); 105 | } 106 | 107 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 108 | { 109 | return this.GetEnumerator(); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/AdjacencyList/AdjacencyList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | //TODO: unweighted adjacency list and weighted adjacency list 8 | namespace DataStructures.AdjacencyList 9 | { 10 | [Serializable] 11 | public class AdjacencyList 12 | { 13 | private readonly Dictionary> dict; 14 | 15 | public IList Vertices 16 | { 17 | get { return dict.Keys.ToList(); } 18 | } 19 | 20 | public int Count 21 | { 22 | get { return dict.Count; } 23 | } 24 | 25 | public AdjacencyList() 26 | { 27 | dict = new Dictionary>(); 28 | } 29 | 30 | public AdjacencyList(int capacity) 31 | { 32 | Contract.Requires(capacity > 0); 33 | 34 | dict = new Dictionary>(capacity); 35 | } 36 | 37 | public void AddVertex(T vertex) 38 | { 39 | Contract.Requires(vertex != null); 40 | 41 | if(dict.ContainsKey(vertex)) 42 | { 43 | return; 44 | } 45 | dict[vertex] = new HashSet(); 46 | } 47 | 48 | public void AddEdge(T vertex1, T vertex2) 49 | { 50 | Contract.Requires(vertex1 != null); 51 | Contract.Requires(vertex2 != null); 52 | 53 | if (!dict.ContainsKey(vertex1)) 54 | { 55 | dict[vertex1] = new HashSet(); 56 | } 57 | if (!dict.ContainsKey(vertex2)) 58 | { 59 | dict[vertex2] = new HashSet(); 60 | } 61 | dict[vertex1].Add(vertex2); 62 | dict[vertex2].Add(vertex1); 63 | } 64 | 65 | public bool IsNeighbourOf(T vertex, T neighbour) 66 | { 67 | Contract.Requires(vertex != null); 68 | Contract.Requires(neighbour != null); 69 | 70 | return dict.ContainsKey(vertex) && dict[vertex].Contains(neighbour); 71 | } 72 | 73 | public IList GetNeighbours(T vertex) 74 | { 75 | Contract.Requires(vertex != null); 76 | 77 | return dict.ContainsKey(vertex)? dict[vertex].ToList(): new List(); 78 | } 79 | 80 | public IList this[T vertex] 81 | { 82 | get 83 | { 84 | return GetNeighbours(vertex); 85 | } 86 | set 87 | { 88 | Contract.Requires(vertex != null); 89 | 90 | dict[vertex] = new HashSet(value); 91 | } 92 | } 93 | 94 | public IList> GetEdgeList() 95 | { 96 | var list = new List>(); 97 | 98 | foreach (var entry in dict) 99 | { 100 | var key = entry.Key; 101 | var hashSet = entry.Value; 102 | list.AddRange(hashSet.Select(hashEntry => new Tuple(key, hashEntry))); 103 | } 104 | return list; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/List/SortedListTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using DataStructures.ListSpace; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace DataStructures.SortedList.Tests 10 | { 11 | [TestClass()] 12 | public class SortedListTests 13 | { 14 | private SortedList _sortedList = new SortedList(); 15 | private readonly int[] _nodes = new int[] { 1, 2, 3, 4, 5, 6 }; 16 | 17 | [TestInitialize, TestCleanup] 18 | protected void UnLoadInput() 19 | { 20 | _sortedList = _sortedList = new SortedList(); 21 | } 22 | 23 | protected void LoadInput() 24 | { 25 | foreach (var node in _nodes) 26 | { 27 | _sortedList.Add(node); 28 | } 29 | } 30 | 31 | [TestMethod] 32 | public void AddElementTest() 33 | { 34 | const int elementToAdd = 1; 35 | _sortedList.Add(elementToAdd); 36 | const int expectedSize = 1; 37 | Assert.AreEqual(expectedSize, _sortedList.Count, "Size do not match the expected value after one insert"); 38 | } 39 | 40 | [TestMethod] 41 | public void AddSameElementTest() 42 | { 43 | const int elementToAdd = 1; 44 | _sortedList.Add(elementToAdd); 45 | _sortedList.Add(elementToAdd); 46 | const int expectedSize = 2; 47 | Assert.AreEqual(expectedSize, _sortedList.Count, "Size do not match the expected value after double insert"); 48 | } 49 | 50 | [TestMethod] 51 | public void AddElementsOrderedTest() 52 | { 53 | for (var i = _nodes.Length - 1; i >= 0; i--) 54 | { 55 | _sortedList.Add(i); 56 | } 57 | const int firstIndexToCheck = 0; 58 | const int secondIndexToCheck = 1; 59 | var size = _sortedList.Count; 60 | var firstElement = _sortedList.ElementAt(firstIndexToCheck); 61 | var secondElement = _sortedList.ElementAt(secondIndexToCheck); 62 | 63 | Assert.IsTrue(firstElement <= secondElement, "List not sorted"); 64 | } 65 | 66 | [TestMethod] 67 | public void ClearTest() 68 | { 69 | LoadInput(); 70 | _sortedList.Clear(); 71 | const int expectedCount = 0; 72 | Assert.AreEqual(expectedCount, _sortedList.Count, "Cleared list has size <> 0"); 73 | } 74 | 75 | [TestMethod] 76 | public void ContainTest() 77 | { 78 | const int elementToAdd = 1; 79 | _sortedList.Add(elementToAdd); 80 | Assert.IsTrue(_sortedList.Contains(elementToAdd), "List does not contain the added element"); 81 | } 82 | 83 | [TestMethod] 84 | public void RemoveTest() 85 | { 86 | const int element = 1; 87 | _sortedList.Add(element); 88 | _sortedList.Remove(element); 89 | Assert.IsFalse(_sortedList.Contains(element), "List still contains the rimoved element"); 90 | } 91 | 92 | 93 | [TestMethod] 94 | public void RemoveNonAddedTest() 95 | { 96 | const int addedElement = 1; 97 | _sortedList.Add(addedElement); 98 | const int toRemoveElement = 2; 99 | const int expectedSize = 1; 100 | _sortedList.Remove(toRemoveElement); 101 | Assert.AreEqual(expectedSize, _sortedList.Count, "Removing a non-present element makes the count non correct"); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/IntervalTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | 6 | 7 | namespace DataStructures.IntervalTreeSpace 8 | { 9 | public partial class IntervalTree 10 | { 11 | /// 12 | /// Node for interval tree 13 | /// 14 | [Serializable] 15 | private class Node : IEquatable, IComparable, IComparable 16 | { 17 | private List rightSortedIntervals; 18 | private List leftSortedIntervals; 19 | 20 | public double X { get; set; } 21 | public ReadOnlyCollection Intervals 22 | { 23 | get { return new ReadOnlyCollection(leftSortedIntervals); } 24 | } 25 | public Node Left { get; set; } 26 | public Node Right { get; set; } 27 | 28 | 29 | public Node(double x) 30 | { 31 | this.X = x; 32 | rightSortedIntervals = new List(); 33 | leftSortedIntervals = new List(); 34 | } 35 | 36 | public void AddInterval(Interval interval) 37 | { 38 | rightSortedIntervals.Add(interval); 39 | rightSortedIntervals.Sort(new EndComparer()); 40 | 41 | leftSortedIntervals.Add(interval); 42 | leftSortedIntervals.Sort(new StartComparer()); 43 | } 44 | 45 | public IList GetIntervals(double x) 46 | { 47 | var intervals = new List(); 48 | if (x < X) 49 | { 50 | foreach (var interval in leftSortedIntervals) 51 | { 52 | if (interval.Start > x) 53 | { 54 | break; 55 | } 56 | intervals.Add(interval); 57 | } 58 | } 59 | else if (x > X) 60 | { 61 | foreach (var interval in rightSortedIntervals) 62 | { 63 | if (interval.End < x) 64 | { 65 | break; 66 | } 67 | intervals.Add(interval); 68 | } 69 | } 70 | else 71 | { 72 | intervals.Concat(leftSortedIntervals); 73 | } 74 | return intervals; 75 | } 76 | 77 | public bool IsInInterval(Interval interval) 78 | { 79 | return X >= interval.Start && X <= interval.End; 80 | } 81 | 82 | public void Remove(Interval interval) 83 | { 84 | rightSortedIntervals.Remove(interval); 85 | leftSortedIntervals.Remove(interval); 86 | } 87 | 88 | public bool Equals(Node other) 89 | { 90 | 91 | throw new NotImplementedException(); 92 | } 93 | 94 | public int CompareTo(Interval other) 95 | { 96 | if (other.Start > X) 97 | { 98 | return -1; 99 | } 100 | else if (other.End < X) 101 | { 102 | return 1; 103 | } 104 | return 0; 105 | } 106 | 107 | public int CompareTo(Node other) 108 | { 109 | if (other.X > X) 110 | { 111 | return -1; 112 | } 113 | else if (other.X < X) 114 | { 115 | return 1; 116 | } 117 | return 0; 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/Children.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | 6 | namespace DataStructures.RegionQuadTreeSpace 7 | { 8 | public partial class RegionQuadTree 9 | { 10 | [Serializable] 11 | private class Children : IEnumerable> 12 | where T : IComparable, IEquatable 13 | { 14 | public Node Parent { get; set; } 15 | public Node TopLeft { get; set; } 16 | public Node TopRight { get; set; } 17 | public Node BottomLeft { get; set; } 18 | public Node BottomRight { get; set; } 19 | 20 | public Children(Rectangle region, Node parent) 21 | { 22 | var topLeftTopPoint = region.TopLeftPoint; 23 | var topRightTopPoint = new Point(region.TopLeftPoint.X + region.Width / 2, region.TopLeftPoint.Y); 24 | var bottomLeftTopPoint = new Point(region.TopLeftPoint.X, region.TopLeftPoint.Y + region.Height / 2); 25 | var bottomRightTopPoint = new Point(region.TopLeftPoint.X + region.Width / 2, region.TopLeftPoint.Y + region.Height / 2); 26 | 27 | var topLeftRectangle = new Rectangle(topLeftTopPoint, region.Width / 2, region.Height / 2); 28 | var topRightRectangle = new Rectangle(topRightTopPoint, region.Width / 2, region.Height / 2); 29 | var bottomLeftRectangle = new Rectangle(bottomLeftTopPoint, region.Width / 2, region.Height / 2); 30 | var bottomRightRectangle = new Rectangle(bottomRightTopPoint, region.Width / 2, region.Height / 2); 31 | 32 | Parent = parent; 33 | 34 | TopLeft = new Node(topLeftRectangle, default(T), parent); 35 | TopRight = new Node(topRightRectangle, default(T), parent); 36 | BottomLeft = new Node(bottomLeftRectangle, default(T), parent); 37 | BottomRight = new Node(bottomRightRectangle, default(T), parent); 38 | } 39 | 40 | public Children(Node parent, Node topLeft, Node topRight, 41 | Node bottomLeft, Node bottomRight) 42 | { 43 | Parent = parent; 44 | TopLeft = topLeft; 45 | TopRight = topRight; 46 | BottomLeft = bottomLeft; 47 | BottomRight = bottomRight; 48 | } 49 | 50 | /// 51 | /// Find the child containing point, otherwise null 52 | /// 53 | /// 54 | /// 55 | public virtual Node GetContainingChild(Point point) 56 | { 57 | List> childrenList = ToList(); 58 | 59 | foreach (var child in childrenList) 60 | { 61 | if (child.IsInRegion(point)) 62 | { 63 | return child; 64 | } 65 | } 66 | return null; 67 | } 68 | 69 | /// 70 | /// Returns all the children as list of nodes 71 | /// 72 | /// 73 | public List> ToList() 74 | { 75 | Contract.Ensures(Contract.Result>>() != null); 76 | 77 | return new List> 78 | { 79 | TopLeft, 80 | TopRight, 81 | BottomLeft, 82 | BottomRight, 83 | }; 84 | } 85 | 86 | public IEnumerator> GetEnumerator() 87 | { 88 | return this.ToList().GetEnumerator(); 89 | } 90 | 91 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 92 | { 93 | return this.GetEnumerator(); 94 | } 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/Children.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | 6 | namespace DataStructures.QuadTreeSpace 7 | { 8 | public partial class QuadTree 9 | { 10 | [Serializable] 11 | private class Children : IEnumerable> 12 | { 13 | public Node Parent { get; set; } 14 | public Node TopLeft { get; set; } 15 | public Node TopRight { get; set; } 16 | public Node BottomLeft { get; set; } 17 | public Node BottomRight { get; set; } 18 | 19 | public Children(Rectangle region, Node parent, int maximumValuesPerNode) 20 | { 21 | var topLeftTopPoint = region.TopLeftPoint; 22 | var topRightTopPoint = new Point(region.TopLeftPoint.X + region.Width / 2, region.TopLeftPoint.Y); 23 | var bottomLeftTopPoint = new Point(region.TopLeftPoint.X, region.TopLeftPoint.Y + region.Height / 2); 24 | var bottomRightTopPoint = new Point(region.TopLeftPoint.X + region.Width / 2, region.TopLeftPoint.Y + region.Height / 2); 25 | 26 | var topLeftRectangle = new Rectangle(topLeftTopPoint, region.Width / 2, region.Height / 2); 27 | var topRightRectangle = new Rectangle(topRightTopPoint, region.Width / 2, region.Height / 2); 28 | var bottomLeftRectangle = new Rectangle(bottomLeftTopPoint, region.Width / 2, region.Height / 2); 29 | var bottomRightRectangle = new Rectangle(bottomRightTopPoint, region.Width / 2, region.Height / 2); 30 | 31 | Parent = parent; 32 | 33 | TopLeft = new Node(topLeftRectangle, parent, maximumValuesPerNode); 34 | TopRight = new Node(topRightRectangle, parent, maximumValuesPerNode); 35 | BottomLeft = new Node(bottomLeftRectangle, parent, maximumValuesPerNode); 36 | BottomRight = new Node(bottomRightRectangle, parent, maximumValuesPerNode); 37 | } 38 | 39 | public Children(Node parent, Node topLeft, Node topRight, 40 | Node bottomLeft, Node bottomRight) 41 | { 42 | Parent = parent; 43 | TopLeft = topLeft; 44 | TopRight = topRight; 45 | BottomLeft = bottomLeft; 46 | BottomRight = bottomRight; 47 | } 48 | 49 | /// 50 | /// Find the child containing point, otherwise null 51 | /// 52 | /// 53 | /// Null if no children contains the point 54 | public virtual Node GetContainingChild(Point point) 55 | { 56 | var childrenList = ToList(); 57 | 58 | foreach (var child in childrenList) 59 | { 60 | if (child.IsInRegion(point)) 61 | { 62 | return child; 63 | } 64 | } 65 | return null; 66 | } 67 | 68 | /// 69 | /// Returns all the children as list of nodes 70 | /// 71 | /// 72 | public List> ToList() 73 | { 74 | Contract.Ensures(Contract.Result>>() != null); 75 | 76 | return new List> 77 | { 78 | TopLeft, 79 | TopRight, 80 | BottomLeft, 81 | BottomRight, 82 | }; 83 | } 84 | 85 | public IEnumerator> GetEnumerator() 86 | { 87 | return this.ToList().GetEnumerator(); 88 | } 89 | 90 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 91 | { 92 | return this.GetEnumerator(); 93 | } 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/List/MoveToFrontListTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace DataStructures.MoveToFrontListSpace.Tests 10 | { 11 | [TestClass()] 12 | public class MoveToFrontListTests 13 | { 14 | private MoveToFrontList _moveToFrontList = new MoveToFrontList(); 15 | private readonly int[] _nodes = new int[] { 1, 4, 5, 2, 3, 6 }; 16 | 17 | [TestInitialize, TestCleanup] 18 | protected void UnLoadInput() 19 | { 20 | _moveToFrontList = new MoveToFrontList(); 21 | } 22 | 23 | protected void LoadInput() 24 | { 25 | foreach (var node in _nodes) 26 | { 27 | _moveToFrontList.Add(node); 28 | } 29 | } 30 | 31 | [TestMethod] 32 | public void AddElementTest() 33 | { 34 | const int elementToAdd = 1; 35 | _moveToFrontList.Add(elementToAdd); 36 | const int expectedSize = 1; 37 | Assert.AreEqual(expectedSize, _moveToFrontList.Count, "Size do not match the expected value after one insert"); 38 | } 39 | 40 | [TestMethod] 41 | public void AddSameElementTest() 42 | { 43 | const int elementToAdd = 1; 44 | _moveToFrontList.Add(elementToAdd); 45 | _moveToFrontList.Add(elementToAdd); 46 | const int expectedSize = 2; 47 | Assert.AreEqual(expectedSize, _moveToFrontList.Count, "Size do not match the expected value after double insert"); 48 | } 49 | 50 | [TestMethod] 51 | public void AddElementsFrontTest() 52 | { 53 | for (var i = _nodes.Length - 1; i >= 0; i--) 54 | { 55 | _moveToFrontList.Add(_nodes[i]); 56 | } 57 | const int firstIndexToCheck = 0; 58 | const int secondIndexToCheck = 1; 59 | 60 | var firstNodeValue = _nodes[firstIndexToCheck]; 61 | var secondNodeValue = _nodes[secondIndexToCheck]; 62 | 63 | var myArray = new int[_moveToFrontList.Count]; 64 | _moveToFrontList.CopyTo(myArray, 0); 65 | 66 | var firstValue = myArray[_nodes.Length - 1 - firstIndexToCheck]; 67 | var secondValue = myArray[_nodes.Length - 1 - secondIndexToCheck]; 68 | 69 | Assert.AreEqual(firstNodeValue,firstValue, "Values not brough to the front(first element)"); 70 | Assert.AreEqual(secondNodeValue, secondValue, "Values not brough to the front(second element)"); 71 | } 72 | 73 | [TestMethod] 74 | public void ClearTest() 75 | { 76 | LoadInput(); 77 | _moveToFrontList.Clear(); 78 | const int expectedCount = 0; 79 | Assert.AreEqual(expectedCount, _moveToFrontList.Count, "Cleared list has size <> 0"); 80 | } 81 | 82 | [TestMethod] 83 | public void ContainTest() 84 | { 85 | const int elementToAdd = 1; 86 | _moveToFrontList.Add(elementToAdd); 87 | Assert.IsTrue(_moveToFrontList.Contains(elementToAdd), "List does not contain the added element"); 88 | } 89 | 90 | [TestMethod] 91 | public void RemoveTest() 92 | { 93 | const int element = 1; 94 | _moveToFrontList.Add(element); 95 | _moveToFrontList.Remove(element); 96 | Assert.IsFalse(_moveToFrontList.Contains(element), "List still contains the rimoved element"); 97 | } 98 | 99 | 100 | [TestMethod] 101 | public void RemoveNonAddedTest() 102 | { 103 | const int addedElement = 1; 104 | _moveToFrontList.Add(addedElement); 105 | const int toRemoveElement = 2; 106 | const int expectedSize = 1; 107 | _moveToFrontList.Remove(toRemoveElement); 108 | Assert.AreEqual(expectedSize, _moveToFrontList.Count, "Removing a non-present element makes the count non correct"); 109 | } 110 | 111 | 112 | 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/List/SortedList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | namespace DataStructures.ListSpace 6 | { 7 | /// 8 | /// Use insertion sort for every element added 9 | /// 10 | /// 11 | [Serializable] 12 | public class SortedList : IEnumerable, ICollection 13 | where T : IComparable 14 | { 15 | private List list; 16 | 17 | public int Capacity 18 | { 19 | get { return list.Capacity; } 20 | } 21 | 22 | bool ICollection.Remove(T item) 23 | { 24 | var success = ((ICollection)list).Remove(item); 25 | return success; 26 | } 27 | 28 | public int Count 29 | { 30 | get { return list.Count; } 31 | } 32 | 33 | public bool IsReadOnly { get; private set; } 34 | public bool IsSynchronized { get { return false; } } 35 | 36 | [ContractInvariantMethod] 37 | private void ObjectInvariant() 38 | { 39 | Contract.Invariant(Count >= 0); 40 | Contract.Invariant(Capacity >= 0); 41 | } 42 | 43 | public SortedList() 44 | { 45 | list = new List(); 46 | } 47 | 48 | public SortedList(int capacity) 49 | { 50 | Contract.Requires(capacity > 0); 51 | 52 | list = new List(capacity); 53 | } 54 | 55 | public SortedList(IEnumerable list) 56 | { 57 | Contract.Requires(list != null); 58 | 59 | this.list = new List(list); 60 | this.list.Sort(); 61 | } 62 | 63 | public void Add(T element) 64 | { 65 | Contract.Requires(element != null); 66 | 67 | var count = 0; 68 | //search for the previous element only when there are other elements in the list 69 | if(list.Count>0){ 70 | for (var i = 0; i < list.Count; i++, count++) 71 | { 72 | if (element.CompareTo(list[i]) <= 0) 73 | { 74 | count = i; 75 | break; 76 | } 77 | } 78 | if(count>0) 79 | Contract.Assert(list[count-1].CompareTo(element) <= 0); 80 | } 81 | list.Insert(count, element); 82 | } 83 | 84 | public void Clear() 85 | { 86 | list = new List(); 87 | } 88 | 89 | public bool Contains(T item) 90 | { 91 | return list.Contains(item); 92 | } 93 | 94 | public void CopyTo(T[] array, int arrayIndex) 95 | { 96 | Contract.Requires(array != null, "array is null"); 97 | Contract.Requires(arrayIndex >= 0, "arrayIndex less than 0"); 98 | 99 | for (var i = arrayIndex; i < list.Count; i++) 100 | { 101 | array[i] = list[i]; 102 | } 103 | } 104 | 105 | public void Remove(T element) 106 | { 107 | Contract.Requires(element != null); 108 | 109 | list.Remove(element); 110 | } 111 | 112 | public void CopyTo(Array array, int index) 113 | { 114 | Contract.Requires(array != null, "array is null"); 115 | Contract.Requires(index >= 0, "arrayIndex less than 0"); 116 | Contract.Requires(array.Length < Count, "array not big enough"); 117 | 118 | int i = index; 119 | foreach (T element in list) 120 | { 121 | array.SetValue(element, i++); 122 | } 123 | } 124 | 125 | public IEnumerator GetEnumerator() 126 | { 127 | return list.GetEnumerator(); 128 | } 129 | 130 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 131 | { 132 | return this.GetEnumerator(); 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BinarySearchTree/BinarySearchTreeTranspose.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BinarySearchTreeSpace 6 | { 7 | /// 8 | /// A binary search tree which moves accessed element a level closer to root 9 | /// by using appropriate rotation 10 | /// 11 | [Serializable] 12 | public class BinarySearchTreeTranspose : BinarySearchTree 13 | where TKey : IComparable, IEquatable 14 | { 15 | private Node Transpose(Node node) 16 | { 17 | Node parent = node.Parent; 18 | if (parent.Left == node) 19 | { 20 | //Left child 21 | //Rotate right 22 | return RotateRight(parent); 23 | } 24 | else if (parent.Right == node) 25 | { 26 | return RotateLeft(parent); 27 | } 28 | else 29 | { 30 | Contract.Assert(false); 31 | return null; 32 | } 33 | } 34 | 35 | private void Reorient(Node node) 36 | { 37 | if (node == null) 38 | { 39 | return; 40 | } 41 | if (node == root) 42 | { 43 | return; 44 | } 45 | Node parent = node.Parent; 46 | if (parent == root) 47 | { 48 | root = Transpose(node); 49 | } 50 | else 51 | { 52 | if (parent.Parent.Right == parent) 53 | { 54 | parent.Parent.Right = Transpose(node); 55 | } 56 | else if (parent.Parent.Left == parent) 57 | { 58 | parent.Parent.Left = Transpose(node); 59 | } 60 | else 61 | { 62 | Contract.Assert(false); 63 | } 64 | } 65 | } 66 | 67 | private Node RotateLeft(Node root) 68 | { 69 | if (root == null) 70 | { 71 | return null; 72 | } 73 | //temp- original node to be swapped with 74 | Node temp = root.Right; 75 | Node tempLeft = temp.Left; 76 | root.Right = tempLeft; 77 | if (tempLeft != null) 78 | { 79 | tempLeft.Parent = root; 80 | } 81 | 82 | temp.Left = root; 83 | temp.Parent = root.Parent; 84 | root.Parent = temp; 85 | return temp; 86 | } 87 | 88 | private Node RotateRight(Node root) 89 | { 90 | if (root == null) 91 | { 92 | return null; 93 | } 94 | //temp- original node to be swapped with 95 | Node temp = root.Left; 96 | Node tempRight = temp.Right; 97 | 98 | root.Left = tempRight; 99 | if (tempRight != null) 100 | { 101 | tempRight.Parent = root; 102 | } 103 | 104 | temp.Right = root; 105 | temp.Parent = root.Parent; 106 | root.Parent = temp; 107 | return temp; 108 | } 109 | 110 | /// 111 | /// Find element in BST, returns false if not found 112 | /// 113 | /// Element to be found 114 | /// 115 | public override bool Find(TKey element, out TValue value) 116 | { 117 | Contract.Requires(element != null, "BST can't have null values"); 118 | Node node = FindNode(element); 119 | Reorient(node); 120 | if (node != null) 121 | { 122 | value = node.Value; 123 | return true; 124 | } 125 | else 126 | { 127 | value = default(TValue); 128 | return false; 129 | } 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/QuadTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | 6 | namespace DataStructures.QuadTreeSpace 7 | { 8 | public partial class QuadTree 9 | { 10 | /// 11 | /// Node of Heap 12 | /// 13 | /// Data type 14 | [Serializable] 15 | private class Node 16 | { 17 | private List values = new List(); 18 | private readonly Rectangle region; 19 | public readonly int MaximumValuesPerNode; 20 | 21 | public IEnumerable Value 22 | { 23 | get { return values.AsReadOnly(); } 24 | } 25 | public int Count 26 | { 27 | get { return values.Count; } 28 | } 29 | public Node Parent { get; set; } 30 | internal Rectangle Region 31 | { 32 | get { return region; } 33 | } 34 | public Children Children { get; set; } 35 | 36 | [ContractInvariantMethod] 37 | private void ObjectInvariant() 38 | { 39 | Contract.Invariant(values != null); 40 | Contract.Invariant(values.Count <= MaximumValuesPerNode); 41 | } 42 | 43 | public Node(Rectangle rectangle, Node parent, int maximumValuesPerNode) 44 | { 45 | Contract.Requires(maximumValuesPerNode > 0); 46 | 47 | Parent = parent; 48 | region = rectangle; 49 | this.MaximumValuesPerNode = maximumValuesPerNode; 50 | Children = new NullChildren(parent); 51 | } 52 | 53 | /// 54 | /// Returns true if the region of the node contains the point 55 | /// other false 56 | /// 57 | /// 58 | /// 59 | public bool IsInRegion(Point p) 60 | { 61 | return region.IsInRectangle(p); 62 | } 63 | 64 | /// 65 | /// Get the child node that contains the point 66 | /// 67 | /// 68 | /// 69 | public Node GetContainingChild(Point point) 70 | { 71 | return Children.GetContainingChild(point); 72 | } 73 | 74 | /// 75 | /// Splits current node into four quadrants 76 | /// 77 | private void SplitRegionIntoChildNodes() 78 | { 79 | Children = new Children(region, this, MaximumValuesPerNode); 80 | } 81 | 82 | public void Add(Point point, T element) 83 | { 84 | Contract.Requires(element != null); 85 | 86 | if (Count == MaximumValuesPerNode) 87 | { 88 | SplitRegionIntoChildNodes(); 89 | } 90 | else 91 | { 92 | values.Add(element); 93 | } 94 | } 95 | 96 | public bool Equals(Node otherNode) 97 | { 98 | if (otherNode == null) 99 | { 100 | return false; 101 | } 102 | return values.Equals(otherNode.Value); 103 | } 104 | 105 | public override bool Equals(object obj) 106 | { 107 | var otherNode = obj as Node; 108 | if (otherNode == null) 109 | { 110 | return false; 111 | } 112 | return values.Equals(otherNode.Value); 113 | } 114 | 115 | public override int GetHashCode() 116 | { 117 | unchecked // Overflow is fine, just wrap 118 | { 119 | int hash = 17; 120 | // Suitable nullity checks etc, of course :) 121 | hash = hash * 23 + values.GetHashCode(); 122 | return hash; 123 | } 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/AdjacencyList/WeightedAdjacencyList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace DataStructures.AdjacencyList 8 | { 9 | [Serializable] 10 | public class WeightedAdjacencyList 11 | where T : class 12 | { 13 | private readonly Dictionary>> dict; 14 | 15 | public IList Vertices 16 | { 17 | get { return dict.Keys.ToList(); } 18 | } 19 | 20 | public int Count 21 | { 22 | get { return dict.Count; } 23 | } 24 | 25 | public WeightedAdjacencyList() 26 | { 27 | dict = new Dictionary>>(); 28 | } 29 | 30 | public WeightedAdjacencyList(int capacity) 31 | { 32 | Contract.Requires(capacity > 0); 33 | 34 | dict = new Dictionary>>(capacity); 35 | } 36 | 37 | public void AddVertex(T vertex) 38 | { 39 | Contract.Requires(vertex != null); 40 | 41 | if(dict.ContainsKey(vertex)) 42 | { 43 | return; 44 | } 45 | dict[vertex] = new HashSet>(); 46 | } 47 | 48 | public Node[] AddEdge(T vertex1, T vertex2, double weight) 49 | { 50 | Contract.Requires(vertex1 != null); 51 | Contract.Requires(vertex2 != null); 52 | //need to return the nodes in order to allow the search for them later on 53 | var weightedEdgeNodes = new Node[2]; 54 | if(!dict.ContainsKey(vertex1)) 55 | { 56 | dict[vertex1] = new HashSet>(); 57 | } 58 | if(!dict.ContainsKey(vertex2)) 59 | { 60 | dict[vertex2] = new HashSet>(); 61 | } 62 | weightedEdgeNodes[0] = new Node(vertex2, weight); 63 | weightedEdgeNodes[1] = new Node(vertex1, weight); 64 | dict[vertex1].Add(weightedEdgeNodes[0]); 65 | dict[vertex2].Add(weightedEdgeNodes[1]); 66 | return weightedEdgeNodes; 67 | } 68 | 69 | public bool IsNeighbourOf(T vertex, Node neighbour) 70 | { 71 | Contract.Requires(vertex != null); 72 | Contract.Requires(neighbour != null); 73 | 74 | return dict.ContainsKey(vertex) && dict[vertex].Contains(neighbour); 75 | } 76 | 77 | public IList GetAllWeights(T vertex) 78 | { 79 | Contract.Requires(vertex != null); 80 | return dict.ContainsKey(vertex) ? 81 | dict[vertex].Select(n =>n.weight).ToList() : 82 | new List(); 83 | } 84 | 85 | public IList> GetNeighbours(T vertex) 86 | { 87 | Contract.Requires(vertex != null); 88 | 89 | return dict.ContainsKey(vertex)? 90 | dict[vertex].Select(n => new Tuple(n.item, n.weight)).ToList() : 91 | new List>(); 92 | } 93 | 94 | public class Node 95 | where T : class 96 | { 97 | public T item; 98 | public readonly double weight; 99 | 100 | public Node(T item, double weight) 101 | { 102 | this.item = item; 103 | this.weight = weight; 104 | } 105 | 106 | public bool Equals(T item) 107 | { 108 | return this.item.Equals(item); 109 | } 110 | 111 | public bool Equals(Node node) 112 | { 113 | return this.item.Equals(node.item) && 114 | (weight == node.weight); 115 | } 116 | 117 | public override bool Equals(object obj) 118 | { 119 | if(obj is T) 120 | { 121 | return item.Equals(obj as T); 122 | } 123 | if(obj is Node) 124 | { 125 | return Equals(obj as Node); 126 | } 127 | return false; 128 | } 129 | 130 | public override int GetHashCode() 131 | { 132 | return item.GetHashCode() ^ int.Parse(weight.ToString()); 133 | } 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/RegionQuadTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.RegionQuadTreeSpace 6 | { 7 | public partial class RegionQuadTree 8 | { 9 | /// 10 | /// Node of Heap 11 | /// 12 | /// Data type 13 | [Serializable] 14 | private class Node 15 | where T : IComparable, IEquatable 16 | { 17 | private T val; 18 | private readonly Rectangle region; 19 | 20 | public T Value 21 | { 22 | get { return val; } 23 | internal set 24 | { 25 | Contract.Requires(value != null); 26 | val = value; 27 | } 28 | } 29 | public Node Parent { get; set; } 30 | public Rectangle Region 31 | { 32 | get { return region; } 33 | } 34 | internal Children Children { get; set; } 35 | 36 | public Node(Rectangle rectangle, T val, Node parent) 37 | { 38 | this.val = val; 39 | Parent = parent; 40 | region = rectangle; 41 | Children = new NullChildren(parent); 42 | } 43 | 44 | /// 45 | /// Returns true if the region of the node contains the point 46 | /// other false 47 | /// 48 | /// 49 | /// 50 | public bool IsInRegion(Point p) 51 | { 52 | return region.IsInRectangle(p); 53 | } 54 | 55 | /// 56 | /// Get the child node that contains the point 57 | /// 58 | /// 59 | /// 60 | public Node GetContainingChild(Point point) 61 | { 62 | return Children.GetContainingChild(point); 63 | } 64 | 65 | /// 66 | /// Splits current node into four quadrants 67 | /// 68 | private void SplitRegionIntoChildNodes() 69 | { 70 | Children = new Children(region, this); 71 | 72 | } 73 | 74 | /// 75 | /// Sets data 76 | /// 77 | /// 78 | /// 79 | /// The node containing new data 80 | public Node SetData(Point point, T data) 81 | { 82 | if (val.Equals(default(T)) || val.Equals(data)) 83 | { 84 | val = data; 85 | return this; 86 | } 87 | else 88 | { 89 | SplitRegionIntoChildNodes(); 90 | Node newChild = null; 91 | foreach (var child in Children) 92 | { 93 | if (child.IsInRegion(point)) 94 | { 95 | // 96 | newChild = child; 97 | child.SetData(point, data); 98 | } 99 | else 100 | { 101 | child.SetData(point, val); 102 | } 103 | } 104 | return newChild; 105 | } 106 | } 107 | 108 | public bool Equals(Node otherNode) 109 | { 110 | if (otherNode == null) 111 | { 112 | return false; 113 | } 114 | return val.Equals(otherNode.Value); 115 | } 116 | 117 | public override bool Equals(object obj) 118 | { 119 | Node otherNode = obj as Node; 120 | if (otherNode == null) 121 | { 122 | return false; 123 | } 124 | return val.Equals(otherNode.Value); 125 | } 126 | 127 | public override int GetHashCode() 128 | { 129 | unchecked // Overflow is fine, just wrap 130 | { 131 | int hash = 17; 132 | // Suitable nullity checks etc, of course :) 133 | hash = hash * 23 + val.GetHashCode(); 134 | return hash; 135 | } 136 | } 137 | } 138 | } 139 | } -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/IntervalTree/IntervalTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Diagnostics.Contracts; 5 | using System.Linq; 6 | 7 | 8 | namespace DataStructures.IntervalTreeSpace 9 | { 10 | /// 11 | /// Interval tree 12 | /// 13 | [Serializable] 14 | public partial class IntervalTree 15 | { 16 | private int count; 17 | 18 | public int Count 19 | { 20 | get { return count; } 21 | } 22 | private Node root; 23 | 24 | [ContractInvariantMethod] 25 | private void ObjectInvariant() 26 | { 27 | Contract.Invariant(count >= 0); 28 | } 29 | 30 | public IntervalTree() 31 | { 32 | } 33 | 34 | /// 35 | /// Add an interval to the tree 36 | /// 37 | /// 38 | public void Add(Interval interval) 39 | { 40 | Contract.Ensures(count == Contract.OldValue(count) + 1); 41 | 42 | if (root == null) 43 | { 44 | root = new Node(interval.Median); 45 | root.AddInterval(interval); 46 | count++; 47 | return; 48 | } 49 | 50 | var current = root; 51 | while (true) 52 | { 53 | int temp = current.CompareTo(interval); 54 | if (temp < 0) 55 | { 56 | if (current.Right == null) 57 | { 58 | current.Right = new Node(interval.Median); 59 | current.Right.AddInterval(interval); 60 | count++; 61 | break; 62 | } 63 | current = current.Right; 64 | } 65 | else if (temp > 0) 66 | { 67 | if (current.Left == null) 68 | { 69 | current.Left = new Node(interval.Median); 70 | current.Left.AddInterval(interval); 71 | count++; 72 | break; 73 | } 74 | current = current.Left; 75 | } 76 | else 77 | { 78 | current.AddInterval(interval); 79 | count++; 80 | break; 81 | } 82 | } 83 | } 84 | 85 | private IList Find(Node treeNode, double x) 86 | { 87 | Contract.Ensures(Contract.Result>() != null); 88 | 89 | if (treeNode == null) 90 | { 91 | return new List(); 92 | } 93 | List intervals; 94 | if (x < treeNode.X) 95 | { 96 | intervals = treeNode.GetIntervals(x).ToList(); 97 | intervals.AddRange(Find(treeNode.Left, x)); 98 | } 99 | else if (x > treeNode.X) 100 | { 101 | intervals = treeNode.GetIntervals(x).ToList(); 102 | intervals.AddRange(Find(treeNode.Right, x)); 103 | } 104 | else 105 | { 106 | //all the intervals 107 | intervals = new List(treeNode.Intervals); 108 | } 109 | return intervals; 110 | } 111 | 112 | private Node FindNode(Interval interval) 113 | { 114 | var current = root; 115 | 116 | while (current != null) 117 | { 118 | if (current.X > interval.Start) 119 | { 120 | current = current.Left; 121 | } 122 | else if (current.X < interval.End) 123 | { 124 | current = current.Right; 125 | } 126 | else 127 | { 128 | return current; 129 | } 130 | } 131 | 132 | return null; 133 | } 134 | 135 | /// 136 | /// Remove an interval from tree if it exists, otherwise ignore 137 | /// 138 | /// Interval to be removed 139 | public void Remove(Interval interval) 140 | { 141 | var node = FindNode(interval); 142 | if (node == null) 143 | { 144 | return; 145 | } 146 | node.Remove(interval); 147 | count--; 148 | } 149 | 150 | public IEnumerable Find(double x) 151 | { 152 | var current = root; 153 | return Find(current, x); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/List/MoveToFrontList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | namespace DataStructures.MoveToFrontListSpace 7 | { 8 | /// 9 | /// Moves most recently accessed element to the root 10 | /// 11 | /// 12 | [Serializable] 13 | public class MoveToFrontList : IEnumerable, ICollection 14 | { 15 | private List list; 16 | private readonly object syncRoot = new object(); 17 | 18 | bool ICollection.Remove(T item) 19 | { 20 | var removedItem = ((ICollection) list).Remove(item); 21 | return removedItem; 22 | } 23 | 24 | public int Count 25 | { 26 | get { return list.Count; } 27 | } 28 | 29 | public bool IsReadOnly { get; private set; } 30 | 31 | public int Capacity 32 | { 33 | get { return list.Capacity; } 34 | } 35 | public object SyncRoot 36 | { 37 | get { return syncRoot; } 38 | } 39 | public bool IsSynchronized 40 | { 41 | get { return false; } 42 | } 43 | 44 | public MoveToFrontList() 45 | { 46 | list = new List(); 47 | } 48 | 49 | public MoveToFrontList(int capacity) 50 | { 51 | Contract.Requires(capacity > 0); 52 | 53 | list = new List(capacity); 54 | } 55 | 56 | /// 57 | /// Retrieves specific node and updates that node position 58 | /// 59 | /// 60 | /// null if element isn't in the list 61 | public T Get(T element) 62 | { 63 | Contract.Requires(element != null); 64 | 65 | var node = list.FirstOrDefault(e => e.Equals(element)); 66 | if (node == null) 67 | { 68 | return default(T); 69 | } 70 | list.Remove(node); 71 | list.Insert(0, node); 72 | return node; 73 | } 74 | 75 | /// 76 | /// 77 | /// 78 | /// 79 | public void Add(T element) 80 | { 81 | Contract.Requires(element != null); 82 | 83 | list.Add(element); 84 | } 85 | 86 | public void Clear() 87 | { 88 | list = new List(); 89 | } 90 | 91 | public bool Contains(T item) 92 | { 93 | return list.Contains(item); 94 | } 95 | 96 | public void CopyTo(T[] array, int arrayIndex) 97 | { 98 | Contract.Requires(array != null, "array"); 99 | Contract.Requires(arrayIndex >= 0, "index"); 100 | Contract.Requires(arrayIndex <= Count); 101 | 102 | var i = arrayIndex; 103 | foreach (var element in list) 104 | { 105 | array.SetValue(element, i++); 106 | } 107 | } 108 | 109 | /// 110 | /// Removes element from list, throws exception 111 | /// 112 | /// 113 | public void Remove(T element) 114 | { 115 | Contract.Requires(element != null); 116 | 117 | list.Remove(element); 118 | } 119 | 120 | public void CopyTo(Array array, int index) 121 | { 122 | Contract.Requires(array != null, "array"); 123 | Contract.Requires(index >= 0, "index"); 124 | Contract.Requires(index <= Count); 125 | 126 | int i = index; 127 | foreach (var element in list) 128 | { 129 | array.SetValue(element, i++); 130 | } 131 | } 132 | 133 | public IEnumerator GetEnumerator() 134 | { 135 | return list.GetEnumerator(); 136 | } 137 | 138 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 139 | { 140 | return this.GetEnumerator(); 141 | } 142 | } 143 | 144 | public static class MoveToFrontListExtension 145 | { 146 | public static T[] CopyToArray(this MoveToFrontList self) 147 | { 148 | var returnedArray = new T[self.Count]; 149 | var count = 0; 150 | foreach (var element in self) 151 | { 152 | returnedArray[count++] = element; 153 | } 154 | return returnedArray; 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/Queue/DequeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using DataStructures.MoveToFrontListSpace; 7 | using DataStructures.QueueSpace; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace data_structures_csharpTests.Queue 11 | { 12 | [TestClass()] 13 | public class DequeTests 14 | { 15 | private Deque _deque = new Deque(); 16 | private readonly int[] _nodes = new int[] { 1, 4, 5, 2, 3, 6 }; 17 | 18 | [TestInitialize, TestCleanup] 19 | protected void UnLoadInput() 20 | { 21 | _deque = new Deque(); 22 | } 23 | 24 | protected void LoadInput() 25 | { 26 | foreach (var node in _nodes) 27 | { 28 | _deque.AddLast(node); 29 | } 30 | } 31 | 32 | [TestMethod] 33 | public void PeekFirstEmptyTest() 34 | { 35 | var noElement = _deque.PeekFirst; 36 | const int expectedElement = default(int); 37 | Assert.AreEqual(expectedElement, noElement, "Could not peek the first element on an empty list"); 38 | } 39 | 40 | [TestMethod] 41 | public void PeekFirstTest() 42 | { 43 | LoadInput(); 44 | var element = _deque.PeekFirst; 45 | var expectedElement = _nodes[0]; 46 | Assert.AreEqual(expectedElement, element, "Could not peek the first element on a list"); 47 | } 48 | 49 | [TestMethod] 50 | public void PeekLastEmptyTest() 51 | { 52 | var noElement = _deque.PeekLast; 53 | const int expectedElement = default(int); 54 | Assert.AreEqual(expectedElement, noElement, "Could not peek the last element on an empty list"); 55 | } 56 | 57 | [TestMethod] 58 | public void PeekLastTest() 59 | { 60 | LoadInput(); 61 | var element = _deque.PeekLast; 62 | var expectedElement = _nodes[_nodes.Length - 1]; 63 | Assert.AreEqual(expectedElement, element, "Could not peek the last element on a list"); 64 | } 65 | 66 | [TestMethod] 67 | public void AddFirstTest() 68 | { 69 | LoadInput(); 70 | const int element = 11; 71 | _deque.AddFirst(element); 72 | var peekedElement = _deque.PeekFirst; 73 | Assert.AreEqual(element, peekedElement, "Could not peek the first element on a list after AddFirst"); 74 | } 75 | 76 | [TestMethod] 77 | public void AddFirstCountTest() 78 | { 79 | const int element = 11; 80 | _deque.AddFirst(element); 81 | const int expectedSize = 1; 82 | Assert.AreEqual(expectedSize, _deque.Count, "Size does not match 1 after one insert"); 83 | } 84 | 85 | [TestMethod] 86 | public void AddLastTest() 87 | { 88 | LoadInput(); 89 | const int element = 11; 90 | _deque.AddLast(element); 91 | var peekedElement = _deque.PeekLast; 92 | Assert.AreEqual(element, peekedElement, "Could not peek the last element on a list after AddLast"); 93 | } 94 | 95 | [TestMethod] 96 | public void AddLastCountTest() 97 | { 98 | const int element = 11; 99 | _deque.AddLast(element); 100 | const int expectedSize = 1; 101 | Assert.AreEqual(expectedSize, _deque.Count, "Size does not match 1 after one insert"); 102 | } 103 | 104 | [TestMethod] 105 | public void RemoveFirstEmptyTest() 106 | { 107 | const int expectedElement = default(int); 108 | Assert.AreEqual(expectedElement, _deque.RemoveFirst(), "Did not remove get the right value on an empty list with RemoveFirst"); 109 | } 110 | 111 | [TestMethod] 112 | public void RemoveFirstTest() 113 | { 114 | LoadInput(); 115 | const int expectedElement = 11; 116 | _deque.AddFirst(expectedElement); 117 | Assert.AreEqual(expectedElement, _deque.RemoveFirst(), "Did not remove get the right value on a list with RemoveFirst"); 118 | } 119 | 120 | [TestMethod] 121 | public void RemoveLastEmptyTest() 122 | { 123 | const int expectedElement = default(int); 124 | Assert.AreEqual(expectedElement, _deque.RemoveLast(), "Did not remove get the right value on an empty list with RemoveLast"); 125 | } 126 | 127 | [TestMethod] 128 | public void RemovelastTest() 129 | { 130 | LoadInput(); 131 | const int expectedElement = 11; 132 | _deque.AddLast(expectedElement); 133 | Assert.AreEqual(expectedElement, _deque.RemoveLast(), "Did not remove get the right value on a list with RemoveLast"); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BloomFilter/BloomFilter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.Contracts; 5 | using System.IO; 6 | using System.Runtime.Serialization.Formatters.Binary; 7 | using System.Security.Cryptography; 8 | 9 | 10 | namespace DataStructures.BloomFilterSpace 11 | { 12 | [Serializable] 13 | public abstract class BloomFilter 14 | { 15 | private readonly BitArray bits; 16 | private readonly int bitsPerElement; 17 | private readonly int numberOfHashFunctions; 18 | private readonly string[] algorithmNames = 19 | { 20 | "SHA", 21 | "MD5", 22 | "SHA1", 23 | "SHA256", 24 | "SHA384", 25 | }; 26 | 27 | public int BitsPerElement 28 | { 29 | get { return bitsPerElement; } 30 | } 31 | 32 | public int Count { get; private set; } 33 | 34 | public int NumberOfHashes 35 | { 36 | get { return algorithmNames.Length; } 37 | } 38 | 39 | public double FalsePositiveProbability 40 | { 41 | // (1 - e^(-k * n / m)) ^ k 42 | get 43 | { 44 | return Math.Pow((1 - Math.Exp(-NumberOfHashes * (double)Count 45 | / (double)bits.Length)), NumberOfHashes); 46 | } 47 | 48 | } 49 | public abstract object SyncRoot { get; } 50 | 51 | [ContractInvariantMethod] 52 | private void ObjectInvariant() 53 | { 54 | Contract.Invariant(Count >= 0); 55 | } 56 | 57 | public BloomFilter(int bitsPerElement, int numberOfElements) 58 | { 59 | Contract.Requires(bitsPerElement > 0); 60 | Contract.Requires(numberOfElements > 0); 61 | 62 | this.bitsPerElement = bitsPerElement; 63 | bits = new BitArray(bitsPerElement * numberOfElements); 64 | Count = 0; 65 | } 66 | 67 | private byte[] ToBytes(T element) 68 | { 69 | Contract.Requires(element != null); 70 | 71 | BinaryFormatter formatter = new BinaryFormatter(); 72 | MemoryStream memoryStream = new MemoryStream(); 73 | formatter.Serialize(memoryStream, element); 74 | return memoryStream.ToArray(); 75 | } 76 | 77 | private int[] CreateHashes(byte[] bytes) 78 | { 79 | int[] result = new int[numberOfHashFunctions]; 80 | int k = 0; 81 | foreach (string algoName in algorithmNames) 82 | { 83 | byte[] digest; 84 | using (HashAlgorithm algorithm = HashAlgorithm.Create(algoName)) 85 | { 86 | digest = algorithm.ComputeHash(bytes); 87 | } 88 | for (int i = 0; i < digest.Length / 4 && k < numberOfHashFunctions; i++) 89 | { 90 | int h = 0; 91 | for (int j = (i * 4); j < (i * 4) + 4; j++) 92 | { 93 | h <<= 8; 94 | h |= ((int)digest[j]) & 0xFF; 95 | } 96 | result[k] = h; 97 | k++; 98 | } 99 | } 100 | return result; 101 | } 102 | 103 | public void Add(T element) 104 | { 105 | Contract.Requires(element != null); 106 | int[] hashes = CreateHashes(ToBytes(element)); 107 | foreach (int hash in hashes) 108 | { 109 | bits.Set((int)Math.Abs(hash % bits.Length), true); 110 | } 111 | Count++; 112 | } 113 | 114 | public void AddRange(IEnumerable elements) 115 | { 116 | Contract.Requires(elements != null); 117 | 118 | foreach (var element in elements) 119 | { 120 | Add(element); 121 | } 122 | } 123 | 124 | private bool Contains(byte[] bytes) 125 | { 126 | Contract.Requires(bytes != null); 127 | Contract.Requires(bytes.Length > 0); 128 | 129 | int[] hashes = CreateHashes(bytes); 130 | foreach (int hash in hashes) 131 | { 132 | if (!bits.Get((int)Math.Abs(hash % bits.Length))) 133 | { 134 | return false; 135 | } 136 | } 137 | return true; 138 | } 139 | 140 | [Pure] 141 | public bool Contains(T element) 142 | { 143 | Contract.Requires(element != null); 144 | return Contains(ToBytes(element)); 145 | } 146 | 147 | public void Clear() 148 | { 149 | bits.SetAll(false); 150 | Count = 0; 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/Heap/HeapTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using DataStructures.HeapSpace; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using System.Diagnostics.Contracts; 9 | 10 | namespace DataStructures.Heap.Tests 11 | { 12 | [TestClass()] 13 | public class HeapTests 14 | { 15 | private Heap _heap = new Heap(); 16 | private readonly int[] _input = new int[] { 10, 0, 2, 26, -1, -6, 1, 24, 25, 44, 100 }; 17 | 18 | protected void UnLoadInput() 19 | { 20 | _heap = new Heap(); 21 | Contract.Assert(_heap != null, "Heap initialisation failed"); 22 | } 23 | 24 | protected void LoadInput() 25 | { 26 | Contract.Assert(_heap != null, "Heap cannot be null"); 27 | _heap = new Heap(); 28 | foreach (var i in _input) 29 | { 30 | _heap.Add(i); 31 | } 32 | } 33 | 34 | [TestMethod()] 35 | public void AddTest() 36 | { 37 | const int key = 0; 38 | var expectedValue = _input[key]; 39 | 40 | //Add first element 41 | UnLoadInput(); 42 | _heap.Add(_input[key]); 43 | var actualCount = _heap.Count; 44 | var expectedCount = 1; 45 | Assert.IsTrue(_heap.Peek == expectedValue, "The added element was not found in the heap"); 46 | Assert.AreEqual(_heap.GetMin(), expectedValue, "The extracted element: "+ _heap.GetMin() + " does not equal the inserted one " +expectedValue); 47 | Assert.AreEqual(expectedCount, actualCount, "Invalid count in adding first element"); 48 | 49 | //Add with many data 50 | LoadInput(); 51 | actualCount = _heap.Count; 52 | expectedCount = _input.Length; 53 | Assert.AreEqual(expectedCount, actualCount, "Invalid count in initialising the heap"); 54 | } 55 | 56 | [TestMethod()] 57 | public void RemoveTest() 58 | { 59 | var count = 0; 60 | UnLoadInput(); 61 | 62 | //Removing a nonexisting Item 63 | var actual = _heap.RemoveMin(); 64 | var expected = default(int); 65 | Assert.AreEqual(expected, actual, "Removing non existing item failed."); 66 | 67 | //Test for the existing node 68 | if (_heap.Count == 0) 69 | { 70 | LoadInput(); 71 | } 72 | //Removing a existing Item 73 | count = _heap.Count; 74 | int value; 75 | expected = _input.Min(); 76 | actual = _heap.RemoveMin(); 77 | var actualCount = _heap.Count; 78 | var expectedCount = count - 1; 79 | Assert.AreEqual(expected, actual, "Removing existing item failed."); 80 | Assert.AreEqual(expectedCount, actualCount, "Removing existing item failed- Count mismatch"); 81 | } 82 | 83 | [TestMethod()] 84 | public void GetMinTest() 85 | { 86 | var count = 0; 87 | UnLoadInput(); 88 | 89 | //Removing a nonexisting Item 90 | var actual = _heap.GetMin(); 91 | var expected = default(int); 92 | Assert.AreEqual(expected, actual, "Getting non existing minimum item failed."); 93 | 94 | //Test for the existing node 95 | if (_heap.Count == 0) 96 | { 97 | LoadInput(); 98 | } 99 | //Removing a existing Item 100 | count = _heap.Count; 101 | expected = _input.Min(); 102 | actual = _heap.GetMin(); 103 | var actualCount = _heap.Count; 104 | var expectedCount = count; 105 | Assert.AreEqual(expected, actual, "Getting existing minimum item failed."); 106 | Assert.AreEqual(expectedCount, actualCount, "Getting existing minimum item failed- Count mismatch"); 107 | } 108 | 109 | 110 | 111 | [TestMethod()] 112 | public void GetPeekTest() 113 | { 114 | var count = 0; 115 | UnLoadInput(); 116 | 117 | //Removing a nonexisting Item 118 | var actual = _heap.GetMin(); 119 | var expected = default(int); 120 | Assert.AreEqual(expected, actual, "Peeking non existing item failed."); 121 | 122 | //Test for the existing node 123 | if (_heap.Count == 0) 124 | { 125 | LoadInput(); 126 | } 127 | //Removing a existing Item 128 | count = _heap.Count; 129 | int value; 130 | expected = _input.Min(); 131 | actual = _heap.Peek; 132 | var actualCount = _heap.Count; 133 | var expectedCount = count; 134 | Assert.AreEqual(expected, actual, "Peeking existing item failed."); 135 | Assert.AreEqual(expectedCount, actualCount, "Peeking existing item failed- Count mismatch"); 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/TransposeList/TransposeList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | 5 | 6 | namespace DataStructures.TransposeListSpace 7 | { 8 | /// 9 | /// Linked list which makes most recently accessed element head of the list 10 | /// 11 | /// 12 | [Serializable] 13 | public partial class TransposeList : IEnumerable, ICollection 14 | { 15 | private int count; 16 | private Node dummy = new Node(); 17 | 18 | private Node head; 19 | public int Count 20 | { 21 | get { return count; } 22 | } 23 | 24 | [ContractInvariantMethod] 25 | private void ObjectInvariant() 26 | { 27 | Contract.Invariant(dummy != null); 28 | Contract.Invariant(count >= 0); 29 | } 30 | 31 | public TransposeList() 32 | { 33 | count = 0; 34 | head = dummy; 35 | } 36 | 37 | [Pure] 38 | private Node GetLastNode() 39 | { 40 | Contract.Ensures(Contract.Result>() != null); 41 | 42 | Node current = head; 43 | while (current.Next != null) 44 | { 45 | current = current.Next; 46 | } 47 | return current; 48 | } 49 | 50 | 51 | private void Adjust(Node node) 52 | { 53 | Contract.Requires(node != null); 54 | 55 | if (node.Previous == dummy) 56 | { 57 | //already at the front of the list 58 | return; 59 | } 60 | var temp = node.Previous; 61 | node.Previous = node.Previous.Previous; 62 | temp.Next = node.Next; 63 | node.Next = temp; 64 | temp.Previous = node; 65 | } 66 | 67 | [Pure] 68 | public T Get(T element) 69 | { 70 | Contract.Requires(element != null); 71 | 72 | var current = head; 73 | while (current != null) 74 | { 75 | if (current.Data.Equals(element)) 76 | { 77 | Adjust(current); 78 | return current.Data; 79 | } 80 | current = current.Next; 81 | } 82 | 83 | return default(T); 84 | } 85 | 86 | [Pure] 87 | private Node GetNode(T element) 88 | { 89 | Contract.Requires(element != null); 90 | 91 | var current = head; 92 | while (current != null) 93 | { 94 | if (current.Data.Equals(element)) 95 | { 96 | return current; 97 | } 98 | current = current.Next; 99 | } 100 | 101 | return null; 102 | } 103 | 104 | public bool Remove(T element) 105 | { 106 | Contract.Requires(element != null); 107 | 108 | var node = GetNode(element); 109 | if (node == null) 110 | { 111 | return false; 112 | } 113 | node.Previous.Next = node.Next; 114 | node.Next.Previous = node.Previous; 115 | count--; 116 | return true; 117 | } 118 | 119 | 120 | public void Add(T data) 121 | { 122 | Contract.Requires(data != null); 123 | Contract.Ensures(count == Contract.OldValue(count) + 1); 124 | 125 | Node node = new Node(data); 126 | var lastNode = GetLastNode(); 127 | lastNode.Next = node; 128 | node.Previous = lastNode; 129 | count++; 130 | } 131 | 132 | [Pure] 133 | public IEnumerator GetEnumerator() 134 | { 135 | var current = head.Next; 136 | while (current != null) 137 | { 138 | yield return current.Data; 139 | current = current.Next; 140 | } 141 | } 142 | 143 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 144 | { 145 | return this.GetEnumerator(); 146 | } 147 | 148 | 149 | public void Clear() 150 | { 151 | head.Next = null; 152 | count = 0; 153 | } 154 | 155 | public bool Contains(T item) 156 | { 157 | var current = head.Next; 158 | 159 | while (current != null) 160 | { 161 | if(current.Data.Equals(item)) 162 | { 163 | return true; 164 | } 165 | current = current.Next; 166 | } 167 | return false; 168 | } 169 | 170 | public void CopyTo(T[] array, int arrayIndex) 171 | { 172 | Contract.Requires(array != null); 173 | 174 | throw new NotImplementedException(); 175 | } 176 | 177 | public bool IsReadOnly 178 | { 179 | get { throw new NotImplementedException(); } 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BinarySearchTree/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.BinarySearchTreeSpace 6 | { 7 | public partial class BinarySearchTree 8 | { 9 | /// 10 | /// Node of Binary Search Tree 11 | /// 12 | /// Data type 13 | [Serializable] 14 | protected class Node 15 | where TKey : IComparable 16 | { 17 | private TKey key; 18 | private TValue val; 19 | 20 | public virtual TKey Key 21 | { 22 | get { return key; } 23 | set 24 | { 25 | Contract.Requires(value != null); 26 | key = value; 27 | } 28 | 29 | } 30 | public virtual TValue Value 31 | { 32 | get { return val; } 33 | set 34 | { 35 | Contract.Requires(value != null); 36 | val = value; 37 | } 38 | } 39 | public virtual int Height { get; set; } 40 | public virtual Node Parent { get; set; } 41 | public virtual Node Left { get; set; } 42 | public virtual Node Right { get; set; } 43 | 44 | protected Node() 45 | { 46 | //Do Nothing 47 | } 48 | 49 | public Node(TKey key, TValue val, Node parent) 50 | { 51 | Contract.Requires(key != null); 52 | Contract.Requires(val != null); 53 | Contract.Requires(parent != null); 54 | this.key = key; 55 | this.val = val; 56 | Parent = parent; 57 | Left = null; 58 | Right = null; 59 | } 60 | 61 | public virtual bool Equals(Node otherNode) 62 | { 63 | if (otherNode == null || otherNode.Parent == null) //Only NullNode have Parent to be null 64 | { 65 | return false; 66 | } 67 | return val.Equals(otherNode.Value); 68 | } 69 | 70 | public override bool Equals(object obj) 71 | { 72 | Node otherNode = obj as Node; 73 | if (otherNode == null || otherNode.Parent == null) //Only NullNode have Parent to be null 74 | { 75 | return false; 76 | } 77 | return val.Equals(otherNode.Value); 78 | } 79 | 80 | public override int GetHashCode() 81 | { 82 | unchecked // Overflow is fine, just wrap 83 | { 84 | int hash = 17; 85 | // Suitable nullity checks etc, of course :) 86 | hash = hash * 23 + key.GetHashCode(); 87 | return hash; 88 | } 89 | } 90 | } 91 | 92 | [Serializable] 93 | protected sealed class NullNode : Node 94 | where TKey : IComparable 95 | { 96 | private TKey key; 97 | private TValue val; 98 | 99 | private static readonly NullNode instance = new NullNode(); 100 | 101 | // Explicit static constructor to tell C# compiler 102 | // not to mark type as beforefieldinit 103 | static NullNode() 104 | { 105 | //Do Nothing 106 | } 107 | 108 | private NullNode() 109 | { 110 | //Do Nothing 111 | } 112 | 113 | public static NullNode Instance 114 | { 115 | get 116 | { 117 | return instance; 118 | } 119 | } 120 | 121 | public override TKey Key 122 | { 123 | get { return key; } 124 | 125 | } 126 | public override TValue Value 127 | { 128 | get { return val; } 129 | } 130 | public override int Height { get { return 0; } } 131 | public override Node Parent { get { return null; } } 132 | public override Node Left { get { return null; } } 133 | public override Node Right { get { return null; } } 134 | 135 | public override bool Equals(Node otherNode) 136 | { 137 | if (otherNode == null) 138 | { 139 | return false; 140 | } 141 | if (otherNode.Parent == null) //Only NullNode have Parent to be null 142 | { 143 | return true; 144 | } 145 | return false; 146 | } 147 | 148 | public override bool Equals(object obj) 149 | { 150 | Node otherNode = obj as Node; 151 | return this.Equals(otherNode); 152 | } 153 | 154 | } 155 | 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/FrequencyList/FrequencyList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.FrequencyListSpace 6 | { 7 | /// 8 | /// Linked List which places frequently accessed items near the head 9 | /// 10 | /// 11 | [Serializable] 12 | public partial class FrequencyList 13 | where T : IComparable 14 | { 15 | private int count; 16 | private readonly Node dummy = new Node(); 17 | 18 | private readonly Node head; 19 | private Node tail; 20 | 21 | public int Count { get { return count; } } 22 | 23 | [ContractInvariantMethod] 24 | private void ObjectInvariant() 25 | { 26 | Contract.Invariant(count >= 0); 27 | } 28 | 29 | public FrequencyList() 30 | { 31 | count = 0; 32 | dummy.AccessCount = Int32.MaxValue; 33 | head = dummy; 34 | } 35 | 36 | private void Adjust(Node node) 37 | { 38 | Contract.Requires(node != null); 39 | 40 | var current = node; 41 | while (current.Previous.AccessCount <= node.AccessCount) 42 | { 43 | current = current.Previous; 44 | } 45 | 46 | //Unlink from previous location 47 | node.Previous.Next = node.Next; 48 | node.Next.Previous = node.Previous; 49 | 50 | //Insert into new location 51 | node.Previous = current.Previous; 52 | node.Next = current; 53 | current.Previous = node; 54 | node.Previous.Next = node; 55 | } 56 | 57 | /// 58 | /// Return if that element exists, otherwise returns null 59 | /// 60 | /// 61 | /// 62 | public bool Exists(T element) 63 | { 64 | Contract.Requires(element != null); 65 | 66 | var current = head; 67 | while (current != null) 68 | { 69 | if (current.Value.Equals(element)) 70 | { 71 | current.AccessCount++; 72 | Adjust(current); 73 | return true; 74 | } 75 | current = current.Next; 76 | } 77 | 78 | return false; 79 | } 80 | 81 | public T Get(int index) 82 | { 83 | Contract.Requires(index >= 0); 84 | Contract.Requires(index < Count); 85 | 86 | return GetNode(index).Value; 87 | } 88 | 89 | private Node GetNode(int index) 90 | { 91 | Contract.Requires(index >= 0); 92 | Contract.Requires(index < Count); 93 | 94 | var current = head; 95 | int i = 0; 96 | while (i < index) 97 | { 98 | current = current.Next; 99 | i++; 100 | } 101 | current.AccessCount++; 102 | Adjust(current); 103 | return current; 104 | } 105 | 106 | /// 107 | /// Get the node containing element, otherwise returns null 108 | /// 109 | /// 110 | /// 111 | public Node GetNode(T element) 112 | { 113 | Contract.Requires(element != null); 114 | 115 | var current = head; 116 | while (current != null) 117 | { 118 | if (current.Value.Equals(element)) 119 | { 120 | return current; 121 | } 122 | current = current.Next; 123 | } 124 | 125 | return null; 126 | } 127 | 128 | /// 129 | /// Remove that element from the list 130 | /// 131 | /// 132 | public void Remove(T element) 133 | { 134 | Contract.Requires(element != null); 135 | Contract.Ensures(count >= 0); 136 | 137 | var node = GetNode(element); 138 | if (node == null) 139 | { 140 | //Element doesn't exist 141 | return; 142 | } 143 | //unlink that node from the list 144 | node.Previous.Next = node.Next; 145 | node.Next.Previous = node.Previous; 146 | count--; 147 | } 148 | 149 | 150 | public void Add(T data) 151 | { 152 | Contract.Requires(data != null); 153 | Contract.Ensures(count == Contract.OldValue(count) + 1); 154 | 155 | Node node = new Node(data); 156 | var lastNode = tail; 157 | lastNode.Next = node; 158 | node.Previous = lastNode; 159 | tail = node; 160 | count++; 161 | } 162 | 163 | public T this[int index] 164 | { 165 | get 166 | { 167 | return Get(index); 168 | } 169 | set 170 | { 171 | 172 | } 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Trie/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Diagnostics.Contracts; 5 | using System.Linq; 6 | 7 | 8 | namespace DataStructures.TrieSpace 9 | { 10 | [Serializable] 11 | public partial class Trie : IEnumerable 12 | { 13 | [Serializable] 14 | private class Node 15 | { 16 | private HashSet children; 17 | private readonly char ch; 18 | private readonly Comparer comparer = new NodeComparer(); 19 | private readonly string wordFromRoot; 20 | 21 | public virtual char Character 22 | { 23 | get { return ch; } 24 | } 25 | public Node Parent { get; private set; } 26 | public virtual string WordFromRoot 27 | { 28 | get { return wordFromRoot; } 29 | } 30 | public virtual ReadOnlyCollection Children 31 | { 32 | get { return new ReadOnlyCollection(children.ToList()); } 33 | } 34 | public Comparer Comparer 35 | { 36 | get { return comparer; } 37 | } 38 | 39 | [ContractInvariantMethod] 40 | private void ObjectInvariant() 41 | { 42 | Contract.Invariant(!string.IsNullOrEmpty(wordFromRoot)); 43 | } 44 | 45 | public Node() 46 | { 47 | } 48 | 49 | 50 | public Node(char ch, string wordFromRoot, Node parent) 51 | { 52 | Contract.Requires(parent != null); 53 | Contract.Requires(wordFromRoot != null); 54 | 55 | children = new HashSet(); 56 | this.ch = ch; 57 | this.Parent = parent; 58 | this.wordFromRoot = wordFromRoot + ch; 59 | } 60 | 61 | /// 62 | /// Check if particular node presents in children 63 | /// 64 | /// character to search in children 65 | /// Null if that children is not present otherwise node having param character 66 | [Pure] 67 | public Node HasChild(char ch) 68 | { 69 | return children.SingleOrDefault(n => n.ch.Equals(ch)); 70 | } 71 | 72 | 73 | /// 74 | /// Add current node to children if it doesn't exist; otherwise return that child node 75 | /// 76 | /// Character to be added to children list 77 | /// Newly added child if it doesn't exist 78 | public Node AddChild(char ch) 79 | { 80 | Contract.Ensures(Contract.Result() != null); 81 | 82 | Node n = HasChild(ch); 83 | if (n == null) 84 | { 85 | Node newNode = new Node(ch, wordFromRoot, this); 86 | children.Add(newNode); 87 | return newNode; 88 | } 89 | return n; 90 | } 91 | 92 | 93 | public void AddNullChild() 94 | { 95 | children.Add(new NullNode(wordFromRoot, this)); 96 | } 97 | 98 | public bool HasNullChild() 99 | { 100 | return (children.SingleOrDefault(n => n.ch.Equals((char)0)) != null); 101 | } 102 | 103 | public void RemoveChild(char ch) 104 | { 105 | children.RemoveWhere(c => c.Character.Equals(ch)); 106 | } 107 | 108 | public void RemoveNullChild() 109 | { 110 | children.RemoveWhere(c => c.Character.Equals((char)0)); 111 | } 112 | 113 | public override int GetHashCode() 114 | { 115 | unchecked // Overflow is fine, just wrap 116 | { 117 | int hash = 17; 118 | // Suitable nullity checks etc, of course :) 119 | hash = hash * 23 + ch.GetHashCode(); 120 | hash = hash * 23 + wordFromRoot.GetHashCode(); 121 | return hash; 122 | } 123 | } 124 | 125 | 126 | public override bool Equals(object obj) 127 | { 128 | Node otherNode = obj as Node; 129 | if (otherNode == null) 130 | { 131 | return false; 132 | } 133 | return wordFromRoot.Equals(otherNode.wordFromRoot) && 134 | ch.Equals(otherNode.ch); 135 | } 136 | 137 | 138 | public override string ToString() 139 | { 140 | return wordFromRoot; 141 | } 142 | 143 | public IList GetChildrenList() 144 | { 145 | return new List(children); 146 | } 147 | 148 | 149 | private sealed class NodeComparer : Comparer 150 | { 151 | public override int Compare(Node x, Node y) 152 | { 153 | Contract.Requires(x != null); 154 | Contract.Requires(y != null); 155 | 156 | return x.Character.CompareTo(y.Character); 157 | } 158 | } 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/HSBT/HeapStructuredBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | 5 | namespace DataStructures.HsbtSpace 6 | { 7 | /// 8 | /// Root < left < right 9 | /// 10 | /// 11 | /// 12 | [Serializable] 13 | public partial class HeapStructuredBinaryTree 14 | where TKey : IComparable, IEquatable 15 | { 16 | private Node root; 17 | 18 | public int Count { get; private set; } 19 | 20 | 21 | [ContractInvariantMethod] 22 | private void ObjectInvariant() 23 | { 24 | Contract.Invariant(Count >= 0); 25 | } 26 | 27 | /// 28 | /// Add keyed value to the tree, updates value if key already exists 29 | /// 30 | /// 31 | /// 32 | public void Add(TKey key, TValue value) 33 | { 34 | Contract.Requires(key != null); 35 | Contract.Requires(value != null); 36 | 37 | if (root == null) 38 | { 39 | root = new Node(key, value, null); 40 | Count++; 41 | return; 42 | } 43 | 44 | var current = root; 45 | while (true) 46 | { 47 | Contract.Assert(current.Key.CompareTo(current.Left.Key) < 0); 48 | Contract.Assert(current.Key.CompareTo(current.Right.Key) < 0); 49 | Contract.Assert(current.Left.Key.CompareTo(current.Right.Key) < 0); 50 | 51 | int compareCurrent = current.Key.CompareTo(key); 52 | if (compareCurrent == 0) 53 | { 54 | current.Value = value; 55 | return; 56 | } 57 | if (compareCurrent < 0) 58 | { 59 | var node = new Node(key, value, current.Parent); 60 | current.Parent.Left = node; 61 | node.Left = current; 62 | Count++; 63 | return; 64 | } 65 | if (current.Left == null) 66 | { 67 | current.Left = new Node(key, value, current); 68 | Count++; 69 | return; 70 | } 71 | if (current.Right == null) 72 | { 73 | current.Right = new Node(key, value, current); 74 | Count++; 75 | return; 76 | } 77 | int compareLeft = current.Left.Key.CompareTo(key); 78 | int compareRight = current.Right.Key.CompareTo(key); 79 | if (compareLeft < 0) 80 | { 81 | //key is less then left element 82 | var node = new Node(key, value, current); 83 | node.Left = current.Left; 84 | current.Left = node; 85 | node.Left = current; 86 | Count++; 87 | return; 88 | } 89 | if (compareLeft < 0 && compareRight > 0) 90 | { 91 | //key is greater than left and smaller than right 92 | current = current.Left; 93 | continue; 94 | } 95 | if (compareRight < 0) 96 | { 97 | //key is greater than right 98 | current = current.Right; 99 | continue; 100 | } 101 | } 102 | } 103 | 104 | public TValue Find(TKey key) 105 | { 106 | Contract.Requires(key != null); 107 | 108 | var current = root; 109 | while (true) 110 | { 111 | Contract.Assert(current.Key.CompareTo(current.Left.Key) < 0); 112 | Contract.Assert(current.Key.CompareTo(current.Right.Key) < 0); 113 | Contract.Assert(current.Left.Key.CompareTo(current.Right.Key) < 0); 114 | 115 | int compare = key.CompareTo(current.Key); 116 | if (compare == 0) 117 | { 118 | //Value found 119 | return current.Value; 120 | } 121 | int compareRight = key.CompareTo(current.Right.Key); 122 | if (compareRight > 0) 123 | { 124 | //Current key is in right sub tree 125 | current = current.Right; 126 | continue; 127 | } 128 | else if (compareRight == 0) 129 | { 130 | return current.Right.Value; 131 | } 132 | int compareLeft = key.CompareTo(current.Left.Key); 133 | if (compareLeft < 0) 134 | { 135 | return default(TValue); 136 | } 137 | else if (compareLeft > 0) 138 | { 139 | //Current key is in left sub tree 140 | current = current.Left; 141 | continue; 142 | } 143 | else 144 | { 145 | return current.Left.Value; 146 | } 147 | } 148 | 149 | return default(TValue); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/Heap/Heap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | 7 | namespace DataStructures.HeapSpace 8 | { 9 | /// 10 | /// Heap 11 | /// 12 | /// 13 | [Serializable] 14 | public partial class Heap 15 | where T : IComparable 16 | { 17 | private Node root; 18 | 19 | public T Peek 20 | { 21 | get 22 | { 23 | return root == null ? default(T) : root.Value; 24 | } 25 | } 26 | public int Count { get; private set; } 27 | 28 | [ContractInvariantMethod] 29 | private void ObjectInvariant() 30 | { 31 | Contract.Invariant(Count >= 0); 32 | } 33 | 34 | /// 35 | /// Adds an element to the heap 36 | /// 37 | /// 38 | public void Add(T element) 39 | { 40 | Contract.Requires(element != null, "element"); 41 | Contract.Ensures(Count == Contract.OldValue(Count) + 1); 42 | 43 | if (root == null) 44 | { 45 | root = new Node(element, null); 46 | Count++; 47 | return; 48 | } 49 | 50 | var queue = new Queue>(); 51 | queue.Enqueue(root); 52 | while (queue.Any()) 53 | { 54 | var node = queue.Dequeue(); 55 | Contract.Assert(node != null); 56 | if (node.Left == null) 57 | { 58 | node.Left = new Node(element, node); 59 | break; 60 | } 61 | else 62 | { 63 | //cannot guarantee heap order before heapify has run 64 | //Contract.Assert(node.Value.CompareTo(node.Left.Value) < 0, "node.Left.Value diff " + node.Value.CompareTo(node.Left.Value) + " was not < 0"); 65 | queue.Enqueue(node.Left); 66 | } 67 | if (node.Right == null) 68 | { 69 | node.Right = new Node(element, node); 70 | break; 71 | } 72 | else 73 | { 74 | //cannot guarantee heap order before heapify has run 75 | //Contract.Assert(node.Value.CompareTo(node.Right.Value) > 0, "node.Right.Value diff " + node.Value.CompareTo(node.Right.Value) + " was not > 0"); 76 | queue.Enqueue(node.Right); 77 | } 78 | } 79 | //Restore heap property 80 | root = Heapify(root); 81 | Count++; 82 | } 83 | 84 | private Node Heapify(Node root) 85 | { 86 | Contract.Requires(root != null, "root was null"); 87 | Contract.Ensures(Contract.Result>() != null); 88 | //don't heapify on null children 89 | if (root.Right == null) 90 | return root; 91 | if (root.Left == null) 92 | return root; 93 | root.Right = Heapify(root.Right); 94 | root.Left = Heapify(root.Left); 95 | int compareRight = root.Value.CompareTo(root.Right.Value); 96 | if (compareRight > 0) 97 | { 98 | //root is bigger than right 99 | SwapData(root, root.Right); 100 | } 101 | int compareLeft = root.Value.CompareTo(root.Left.Value); 102 | if (compareLeft > 0) 103 | { 104 | //root is bigger than left 105 | SwapData(root, root.Left); 106 | } 107 | return root; 108 | } 109 | 110 | private void SwapData(Node node1, Node node2) 111 | { 112 | Contract.Requires(node1 != null, "node1"); 113 | Contract.Requires(node2 != null, "node2"); 114 | 115 | T tempValue = node1.Value; 116 | node1.Value = node2.Value; 117 | node2.Value = tempValue; 118 | } 119 | 120 | public T GetMin() 121 | { 122 | return root == null ? default(T) : root.Value; 123 | } 124 | 125 | private Node LastNode() 126 | { 127 | if (root == null) 128 | { 129 | return null; 130 | } 131 | 132 | Queue> queue = new Queue>(); 133 | queue.Enqueue(root); 134 | Node last = root; 135 | 136 | while (queue.Any()) 137 | { 138 | var current = queue.Dequeue(); 139 | Contract.Assert(current != null); 140 | last = current; 141 | if (current.Left != null) 142 | { 143 | queue.Enqueue(current.Left); 144 | } 145 | if (current.Right != null) 146 | { 147 | queue.Enqueue(current.Right); 148 | } 149 | } 150 | return last; 151 | } 152 | 153 | public T RemoveMin() 154 | { 155 | if (root == null) 156 | { 157 | return default(T); 158 | } 159 | 160 | Node lastNode = LastNode(); 161 | 162 | if (lastNode.Parent.Right == lastNode) 163 | { 164 | lastNode.Parent.Right = null; 165 | } 166 | if (lastNode.Parent.Left == lastNode) 167 | { 168 | lastNode.Parent.Left = null; 169 | } 170 | SwapData(root, lastNode); 171 | root = Heapify(root); 172 | Count--; 173 | return lastNode.Value; 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/CircularBuffer/CircularBuffer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using System.Diagnostics.Contracts; 5 | using System.Collections; 6 | 7 | namespace DataStructures.CircularBufferSpace 8 | { 9 | [Serializable] 10 | public class CircularBuffer : IEnumerable 11 | { 12 | private int getIndex, addIndex; 13 | private T[] buffer; 14 | 15 | public int Count 16 | { get; private set; } 17 | 18 | public int Capacity 19 | { 20 | get; 21 | private set; 22 | } 23 | 24 | public bool IsEmpty 25 | { 26 | get { return (Count == 0); } 27 | } 28 | 29 | [ContractInvariantMethod] 30 | private void ObjectInvariant() 31 | { 32 | Contract.Invariant(Capacity > 0); 33 | Contract.Invariant(Count >= 0); 34 | Contract.Invariant(Count <= Capacity); 35 | } 36 | 37 | /// 38 | /// Instantiates a new circular buffer. 39 | /// 40 | /// The maximum size of the buffer before it begins overwriting itself. 41 | public CircularBuffer(int capacity) 42 | { 43 | Contract.Requires(capacity > 0); 44 | buffer = new T[capacity]; 45 | Capacity = capacity; 46 | Count = 0; 47 | addIndex = 0; 48 | getIndex = 0; 49 | } 50 | 51 | /// 52 | /// Instantiates a new circular buffer with the input collection's capacity and elements. 53 | /// 54 | /// The collection with elements to insert into the buffer. 55 | public CircularBuffer(ICollection collection) 56 | { 57 | Contract.Requires(collection != null && collection.Count > 0); 58 | buffer = new T[collection.Count]; 59 | Capacity = buffer.Length; 60 | Count = 0; 61 | addIndex = 0; 62 | getIndex = 0; 63 | 64 | foreach (var item in collection) 65 | { 66 | Add(item); 67 | } 68 | } 69 | 70 | /// 71 | /// Instantiates a new circular buffer with the input enumerable's capacity and elements. 72 | /// 73 | /// The enumerable with elements to insert into the buffer. 74 | public CircularBuffer(IEnumerable enumerable) 75 | { 76 | var enumCount = enumerable.Count(); 77 | Contract.Requires(enumerable != null && enumCount > 0); 78 | buffer = new T[enumCount]; 79 | Capacity = buffer.Length; 80 | Count = 0; 81 | addIndex = 0; 82 | getIndex = 0; 83 | 84 | foreach (var item in enumerable) 85 | { 86 | Add(item); 87 | } 88 | } 89 | 90 | /// 91 | /// Adds an element to the circular buffer. 92 | /// 93 | public void Add(T item) 94 | { 95 | Contract.Requires(item != null); 96 | buffer[addIndex] = item; 97 | 98 | if (Count < Capacity) 99 | { 100 | Count++; 101 | } 102 | 103 | if (addIndex == getIndex) 104 | { 105 | getIndex = getIndex < Capacity - 1 ? getIndex + 1 : 0; 106 | } 107 | 108 | addIndex = addIndex < Capacity - 1 ? addIndex + 1 : 0; 109 | } 110 | 111 | /// 112 | /// Clears the circular buffer of all elements. 113 | /// 114 | public void Clear() 115 | { 116 | for (int i = 0; i < buffer.Length; i++) 117 | { 118 | buffer[i] = default(T); 119 | } 120 | 121 | Count = 0; 122 | addIndex = 0; 123 | getIndex = 0; 124 | } 125 | 126 | /// 127 | /// Determines whether a sequence contains a specified element by using the default equality comparer. 128 | /// 129 | public bool Contains(T item) 130 | { 131 | Contract.Requires(item != null); 132 | return buffer.Contains(item); 133 | } 134 | 135 | /// 136 | /// Copies the circular buffer to an array starting at the specified index in the destination array. 137 | /// 138 | public void CopyTo(T[] array, int index = 0) 139 | { 140 | Contract.Requires(array != null); 141 | Contract.Requires(index + Count < array.Length); 142 | buffer.CopyTo(array, index); 143 | } 144 | 145 | /// 146 | /// Gets the oldest element in the circular buffer. 147 | /// 148 | public T Get() 149 | { 150 | Contract.Requires(Count > 0); 151 | var retVal = buffer[getIndex]; 152 | buffer[getIndex] = default(T); 153 | getIndex = getIndex < Capacity - 1 ? getIndex + 1 : 0; 154 | return retVal; 155 | } 156 | 157 | /// 158 | /// Supports a simple iteration over a generic collection. 159 | /// 160 | public IEnumerator GetEnumerator() 161 | { 162 | for (int i = 0; i < buffer.Length; i++) 163 | { 164 | yield return buffer[i]; 165 | } 166 | } 167 | 168 | /// 169 | /// Supports a simple iteration over a nongeneric collection. 170 | /// 171 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 172 | { 173 | return this.GetEnumerator(); 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/BinarySearchTree/BinarySearchTreeTransposeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using DataStructures.BinarySearchTreeSpace; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | namespace DataStructures.BinarySearchTreeSpace.Tests 9 | { 10 | [TestClass()] 11 | public class BinarySearchTreeTransposeTests : BinarySearchTreeTests 12 | { 13 | private BinarySearchTreeTranspose binaryTreeTranspose = new BinarySearchTreeTranspose(); 14 | [TestMethod()] 15 | public void FindTestOnLeafNode() 16 | { 17 | UnLoadInput(binaryTreeTranspose); 18 | LoadInput(binaryTreeTranspose); 19 | int value; 20 | //Leaf Node 21 | bool actual = binaryTreeTranspose.Find(-6, out value); 22 | bool expected = true; 23 | int expectedValue = CalculateValue(-6); 24 | Assert.AreEqual(expected, actual, "Invalid result in finding a element with Leaf Node"); 25 | Assert.AreEqual(expectedValue, value, "Invalid value in finding a element Leaf Node"); 26 | 27 | actual = binaryTreeTranspose.ValidateTree(); 28 | Assert.AreEqual(expected, actual, "Validation failed in transpose"); 29 | } 30 | 31 | [TestMethod()] 32 | public void FindTestOnNodeWithOnlyLeftChild() 33 | { 34 | UnLoadInput(binaryTreeTranspose); 35 | LoadInput(binaryTreeTranspose); 36 | int input = -1; 37 | int value; 38 | //Leaf Node 39 | bool actual = binaryTreeTranspose.Find(input, out value); 40 | bool expected = true; 41 | int expectedValue = CalculateValue(input); 42 | Assert.AreEqual(expected, actual, "Invalid result in finding a element with one left child"); 43 | Assert.AreEqual(expectedValue, value, "Invalid value in finding a element one left child"); 44 | 45 | actual = binaryTreeTranspose.ValidateTree(); 46 | Assert.AreEqual(expected, actual, "Validation failed in transpose with one left child"); 47 | } 48 | 49 | [TestMethod()] 50 | public void FindTestOnNodeWithOnlyRightChild() 51 | { 52 | UnLoadInput(binaryTreeTranspose); 53 | LoadInput(binaryTreeTranspose); 54 | int input = 24; 55 | int value; 56 | //Leaf Node 57 | bool actual = binaryTreeTranspose.Find(input, out value); 58 | bool expected = true; 59 | int expectedValue = CalculateValue(input); 60 | Assert.AreEqual(expected, actual, "Invalid result in finding a element with one right child"); 61 | Assert.AreEqual(expectedValue, value, "Invalid value in finding a element one right child"); 62 | 63 | actual = binaryTreeTranspose.ValidateTree(); 64 | Assert.AreEqual(expected, actual, "Validation failed in transpose with one right child"); 65 | } 66 | 67 | [TestMethod()] 68 | public void FindTestOnNodeWithLeftandRightChild() 69 | { 70 | UnLoadInput(binaryTreeTranspose); 71 | LoadInput(binaryTreeTranspose); 72 | int input = 26; 73 | int value; 74 | //Leaf Node 75 | bool actual = binaryTreeTranspose.Find(input, out value); 76 | bool expected = true; 77 | int expectedValue = CalculateValue(input); 78 | Assert.AreEqual(expected, actual, "Invalid result in finding a element with left and right child"); 79 | Assert.AreEqual(expectedValue, value, "Invalid value in finding a element with left and right child"); 80 | 81 | actual = binaryTreeTranspose.ValidateTree(); 82 | Assert.AreEqual(expected, actual, "Validation failed in transpose with left and right child"); 83 | } 84 | 85 | [TestMethod()] 86 | public void FindTestOnRootNode() 87 | { 88 | UnLoadInput(binaryTreeTranspose); 89 | LoadInput(binaryTreeTranspose); 90 | int input = 10; 91 | int value; 92 | //Leaf Node 93 | bool actual = binaryTreeTranspose.Find(input, out value); 94 | bool expected = true; 95 | int expectedValue = CalculateValue(input); 96 | Assert.AreEqual(expected, actual, "Invalid result in finding a element with root node"); 97 | Assert.AreEqual(expectedValue, value, "Invalid value in finding a element with root node"); 98 | 99 | actual = binaryTreeTranspose.ValidateTree(); 100 | Assert.AreEqual(expected, actual, "Validation failed in transpose with root node"); 101 | } 102 | 103 | [TestMethod()] 104 | public void FindTestWithNoNode() 105 | { 106 | UnLoadInput(binaryTreeTranspose); 107 | int input = -1; 108 | int value; 109 | //Leaf Node 110 | bool actual = binaryTreeTranspose.Find(input, out value); 111 | bool expected = false; 112 | Assert.AreEqual(expected, actual, "Invalid result in finding a element a element without any nodes"); 113 | 114 | actual = binaryTreeTranspose.ValidateTree(); 115 | expected = true; 116 | Assert.AreEqual(expected, actual, "Validation failed in transpose without any nodes"); 117 | } 118 | 119 | 120 | [TestMethod()] 121 | public void FindTestWithInvalidValue() 122 | { 123 | UnLoadInput(binaryTreeTranspose); 124 | int input = 55; 125 | int value; 126 | //Leaf Node 127 | bool actual = binaryTreeTranspose.Find(input, out value); 128 | bool expected = false; 129 | Assert.AreEqual(expected, actual, "Invalid result in finding a element a element with invalid value"); 130 | 131 | actual = binaryTreeTranspose.ValidateTree(); 132 | expected = true; 133 | Assert.AreEqual(expected, actual, "Validation failed in transpose with invalid value"); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/List/CircularQueueTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using DataStructures.ListSpace; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace DataStructures.CircularQueueSpace.Tests 6 | { 7 | [TestClass()] 8 | public class CircularQueueTests 9 | { 10 | private CircularQueue _circularQueue = new CircularQueue(); 11 | private readonly int[] _nodes = new int[] { 1, 2, 3, 4, 5, 6 }; 12 | 13 | [TestInitialize, TestCleanup] 14 | protected void UnLoadInput() 15 | { 16 | _circularQueue = new CircularQueue(); 17 | } 18 | 19 | protected void LoadInput() 20 | { 21 | _circularQueue = new CircularQueue(_nodes.Length); 22 | foreach (var node in _nodes) 23 | { 24 | _circularQueue.Enqueue(node); 25 | } 26 | } 27 | 28 | [TestMethod] 29 | public void EnqueueEmptyTest() 30 | { 31 | const int expectedValue = 5; 32 | _circularQueue.Enqueue(expectedValue); 33 | Assert.AreEqual(expectedValue, _circularQueue.Dequeue(), "Could not extract the right element from an empty queue"); 34 | } 35 | 36 | [TestMethod] 37 | public void EnqueueTwiceTest() 38 | { 39 | const int expectedValue = 5; 40 | _circularQueue.Enqueue(expectedValue); 41 | _circularQueue.Enqueue(expectedValue); 42 | Assert.AreEqual(2, _circularQueue.Count, "Could not extract the right element from an empty queue"); 43 | } 44 | 45 | [TestMethod] 46 | public void DequeueTest() 47 | { 48 | LoadInput(); 49 | var expectedValue = _nodes[0]; 50 | Assert.AreEqual(expectedValue, _circularQueue.Dequeue(), "Could not extract the right element from a queue"); 51 | } 52 | 53 | [TestMethod] 54 | public void EnqueueSingleTest() 55 | { 56 | _circularQueue = new CircularQueue(_nodes.Length); 57 | LoadInput(); 58 | const int expectedValue = 5; 59 | _circularQueue.Enqueue(expectedValue); 60 | Assert.AreEqual(expectedValue, _circularQueue.Dequeue(), "Could not extract the right element inserted in a full queue"); 61 | } 62 | 63 | [TestMethod] 64 | [ExpectedException(typeof(InvalidOperationException))] 65 | public void DequeueEmptyTest() 66 | { 67 | _circularQueue.Dequeue(); 68 | } 69 | 70 | [TestMethod] 71 | public void NextIndexEmptyTest() 72 | { 73 | var next = _circularQueue.NextIndex(_circularQueue.Count); 74 | const int expectedNext = 0; 75 | Assert.AreEqual(expectedNext, next, "Next index on empty queue do not match"); 76 | } 77 | 78 | [TestMethod] 79 | public void NextIndexFullTest() 80 | { 81 | _circularQueue = new CircularQueue(_nodes.Length); 82 | var i = 0; 83 | 84 | var next = _circularQueue.NextIndex(null); 85 | var expectedNext = i; 86 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 87 | _circularQueue.Enqueue(i++); 88 | 89 | next = _circularQueue.NextIndex(i-1); 90 | expectedNext = i; 91 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 92 | _circularQueue.Enqueue(i++); 93 | 94 | next = _circularQueue.NextIndex(i-1); 95 | expectedNext = i; 96 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 97 | _circularQueue.Enqueue(i++); 98 | 99 | next = _circularQueue.NextIndex(i-1); 100 | expectedNext = i; 101 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 102 | _circularQueue.Enqueue(i++); 103 | 104 | next = _circularQueue.NextIndex(i-1); 105 | expectedNext = i; 106 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 107 | _circularQueue.Enqueue(i++); 108 | 109 | next = _circularQueue.NextIndex(i-1); 110 | expectedNext = i; 111 | Assert.AreEqual(expectedNext, next, "Could not get the right index at the element - " + i); 112 | } 113 | 114 | [TestMethod] 115 | public void EnqueueFullTest() 116 | { 117 | _circularQueue = new CircularQueue(_nodes.Length); 118 | var i = 0; 119 | 120 | var next = _circularQueue.NextIndex(null); 121 | _circularQueue.Enqueue(i++); 122 | if (next != null) 123 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 124 | 125 | next = _circularQueue.NextIndex(i - 1); 126 | _circularQueue.Enqueue(i++); 127 | if (next != null) 128 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 129 | 130 | next = _circularQueue.NextIndex(i - 1); 131 | _circularQueue.Enqueue(i++); 132 | if (next != null) 133 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 134 | 135 | next = _circularQueue.NextIndex(i - 1); 136 | _circularQueue.Enqueue(i++); 137 | if (next != null) 138 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 139 | 140 | next = _circularQueue.NextIndex(i - 1); 141 | _circularQueue.Enqueue(i++); 142 | if (next != null) 143 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 144 | 145 | next = _circularQueue.NextIndex(i - 1); 146 | _circularQueue.Enqueue(i++); 147 | if (next != null) 148 | Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1)); 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharp/BTree/BTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | 4 | namespace DataStructures.BTreeSpace 5 | { 6 | [Serializable] 7 | public partial class BTree 8 | where TKey : IComparable 9 | { 10 | private readonly int maximumChildrenPerNode; 11 | 12 | private Node root; 13 | 14 | public int MaximumChildrenPerNode 15 | { 16 | get { return maximumChildrenPerNode; } 17 | } 18 | public int Height { get; private set; } 19 | public int Count { get; private set; } 20 | 21 | [ContractInvariantMethod] 22 | private void ObjectInvariant() 23 | { 24 | Contract.Invariant(root != null); 25 | Contract.Invariant(Count >= 0); 26 | Contract.Invariant(Height >= 0); 27 | } 28 | 29 | public BTree() 30 | { 31 | root = new Node(0); 32 | } 33 | 34 | private TValue Search(Node node, TKey key, int ht) 35 | { 36 | Contract.Requires(node != null); 37 | Contract.Requires(key != null); 38 | Contract.Requires(ht >= 0); 39 | 40 | Entry[] children = node.Children; 41 | 42 | // leaf node i.e. external node 43 | if (ht == 0) 44 | { 45 | //search all the keys in leaf nodes 46 | for (int j = 0; j < node.numberOfChildren; j++) 47 | { 48 | if (Equals(key, children[j].Key)) 49 | { 50 | return children[j].Value; 51 | } 52 | } 53 | } 54 | // internal node 55 | else 56 | { 57 | //search all the children 58 | for (int j = 0; j < node.numberOfChildren; j++) 59 | { 60 | if (j + 1 == node.numberOfChildren || Less(key, children[j + 1].Key)) 61 | { 62 | return Search(children[j].ChildNode, key, ht - 1); 63 | } 64 | } 65 | } 66 | //key isn't found 67 | return default(TValue); 68 | } 69 | 70 | private Node Insert(Node node, TKey key, TValue value, int ht) 71 | { 72 | Contract.Requires(node != null); 73 | Contract.Requires(key != null); 74 | Contract.Requires(ht >= 0); 75 | 76 | int j; 77 | var newEntry = new Entry(key, value, null); 78 | 79 | // external node 80 | if (ht == 0) 81 | { 82 | //find a place to insert new element 83 | for (j = 0; j < node.numberOfChildren; j++) 84 | { 85 | if (Less(key, node.Children[j].Key)) 86 | { 87 | break; 88 | } 89 | } 90 | } 91 | // internal node 92 | else 93 | { 94 | for (j = 0; j < node.numberOfChildren; j++) 95 | { 96 | //if it's the last node or less than current node 97 | if ((j + 1 == node.numberOfChildren) || Less(key, node.Children[j + 1].Key)) 98 | { 99 | Node newNode = Insert(node.Children[j++].ChildNode, key, value, ht - 1); 100 | if (newNode == null) 101 | { 102 | return null; 103 | } 104 | newEntry.Key = newNode.Children[0].Key; 105 | newEntry.ChildNode = newNode; 106 | break; 107 | } 108 | } 109 | } 110 | 111 | for (int i = node.numberOfChildren; i > j; i--) 112 | { 113 | //shift right the children to place new children 114 | node.Children[i] = node.Children[i - 1]; 115 | } 116 | node.Children[j] = newEntry; 117 | node.numberOfChildren++; 118 | 119 | if (node.numberOfChildren < MaximumChildrenPerNode) 120 | { 121 | //No need to split the node 122 | return null; 123 | } 124 | else 125 | { 126 | //other hald node after splitting 127 | return Split(node); 128 | } 129 | } 130 | 131 | // split node in half, return the other half 132 | private Node Split(Node h) 133 | { 134 | var t = new Node(MaximumChildrenPerNode / 2); 135 | h.numberOfChildren = MaximumChildrenPerNode / 2; 136 | for (int j = 0; j < MaximumChildrenPerNode / 2; j++) 137 | { 138 | t.Children[j] = h.Children[MaximumChildrenPerNode / 2 + j]; 139 | } 140 | return t; 141 | } 142 | 143 | // insert key-value pair 144 | // add code to check for duplicate keys 145 | public void Add(TKey key, TValue value) 146 | { 147 | Node newNode = Insert(root, key, value, Height); 148 | Count++; 149 | if (newNode == null) return; 150 | 151 | // need to split root 152 | var t = new Node(2); 153 | t.Children[0] = new Entry(root.Children[0].Key, default(TValue), root); 154 | t.Children[1] = new Entry(newNode.Children[0].Key, default(TValue), newNode); 155 | root = t; 156 | Height++; 157 | } 158 | 159 | private bool Less(IComparable k1, TKey k2) 160 | { 161 | return k1.CompareTo(k2) < 0; 162 | } 163 | 164 | private bool Equals(IComparable k1, TKey k2) 165 | { 166 | return k1.CompareTo(k2) == 0; 167 | } 168 | 169 | public TValue this[TKey key] 170 | { 171 | get 172 | { 173 | if (key == null) 174 | { 175 | return default(TValue); 176 | } 177 | return Search(root, key, Height); 178 | } 179 | set 180 | { 181 | Add(key, value); 182 | } 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /data-structures-csharp/data-structures-csharpTests/AdjacencyList/AdjacencyListTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace DataStructures.AdjacencyList.Tests 6 | { 7 | [TestClass()] 8 | public class AdjacencyListTests 9 | { 10 | private AdjacencyList _adjacencyList = new AdjacencyList(); 11 | 12 | private readonly int[] _nodes = new int[] { 1, 2, 3, 4, 5, 6 }; 13 | //private Dictionary> _dictHashSet = new Dictionary>(); 14 | 15 | [TestInitialize, TestCleanup] 16 | protected void UnLoadInput() 17 | { 18 | _adjacencyList = new AdjacencyList(); 19 | } 20 | 21 | protected void LoadInput() 22 | { 23 | //first ensure all the dict are initialized 24 | foreach (var node in _nodes) 25 | { 26 | _adjacencyList.AddVertex(node); 27 | } 28 | //make a link between nodes that have summed values that mod 3 are equals to 0 29 | foreach (var node in _nodes) 30 | { 31 | foreach (var innerNode in _nodes) 32 | { 33 | //when node + innerNode is divisible by three add a link between them 34 | //e.g. 1 will have edges with 2 and 5 35 | if ((node + innerNode) % 3 != 0 || node == innerNode) continue; 36 | _adjacencyList.AddEdge(node, innerNode); 37 | _adjacencyList.AddEdge(innerNode, node); 38 | } 39 | } 40 | } 41 | [TestMethod] 42 | public void NoVertexTest() 43 | { 44 | const int numberOfNodes = 0; 45 | Assert.AreEqual(numberOfNodes, _adjacencyList.Vertices.Count, "Number of nodes different than 0 on an empty list"); 46 | } 47 | 48 | [TestMethod] 49 | public void AddSingleVertexTest() 50 | { 51 | const int node = 1; 52 | _adjacencyList.AddVertex(node); 53 | const int numberOfNodes = 1; 54 | Assert.AreEqual(numberOfNodes, _adjacencyList.Vertices.Count, "Number of nodes different than 1 on a list with one node"); 55 | } 56 | 57 | [TestMethod] 58 | public void AddMultipleVertexesTest() 59 | { 60 | LoadInput(); 61 | var numberOfNodes = _nodes.Length; 62 | Assert.AreEqual(numberOfNodes, _adjacencyList.Vertices.Count, "Number of nodes does not match the expected number"); 63 | } 64 | 65 | [TestMethod] 66 | public void AddEdgeNoNodeTest() 67 | { 68 | //test with one node, no edges 69 | const int expectedEdgeCount = 0; 70 | var nodeEdgeCount = _adjacencyList.GetNeighbours(int.MinValue).Count(); 71 | Assert.AreEqual(expectedEdgeCount, nodeEdgeCount, "Number of edges different from 0 on a list without edges"); 72 | } 73 | 74 | [TestMethod] 75 | public void AddEdgeOutOfRangeTest() 76 | { 77 | //test with one node, no edges 78 | const int node = 1; 79 | _adjacencyList.AddVertex(node); 80 | const int expectedEdgeCount = 0; 81 | var nodeEdgeCount = _adjacencyList.GetEdgeList().Count(tuple => tuple.Item1 == node); 82 | Assert.AreEqual(expectedEdgeCount, nodeEdgeCount, "Number of edges different from 0 on a list without edges"); 83 | } 84 | 85 | [TestMethod] 86 | public void AddDoubleEdgeTest() 87 | { 88 | //test with two nodes, two edges 89 | const int firstNode = 1; 90 | const int secondNode = 2; 91 | _adjacencyList.AddVertex(firstNode); 92 | _adjacencyList.AddVertex(secondNode); 93 | _adjacencyList.AddEdge(firstNode, secondNode); 94 | _adjacencyList.AddEdge(secondNode, firstNode); 95 | const int expectedNumberOfEdges = 1; 96 | var abc = _adjacencyList.GetEdgeList(); 97 | var firstNodeEdgeCount = _adjacencyList.GetEdgeList().Count(tuple => tuple.Item1 == firstNode); 98 | var secondNodeEdgeCount = _adjacencyList.GetEdgeList().Count(tuple => tuple.Item1 == secondNode); 99 | 100 | Assert.AreEqual(expectedNumberOfEdges, firstNodeEdgeCount, "Number of edges different than one for the first node"); 101 | Assert.AreEqual(expectedNumberOfEdges, secondNodeEdgeCount, "Number of edges different than one for the second node"); 102 | } 103 | 104 | [TestMethod] 105 | public void AddSeveralEdgesTest() 106 | { 107 | LoadInput(); 108 | const int node = 1; 109 | const int expectedNumberOfEdgesForNode1 = 2; 110 | var nodeEdgeCount = _adjacencyList.GetEdgeList().Count(tuple => tuple.Item1 == node); 111 | Assert.AreEqual(expectedNumberOfEdgesForNode1, nodeEdgeCount, 112 | "Number of edges for node 1 do not match the expected value"); 113 | } 114 | 115 | [TestMethod] 116 | public void IsNeighbourOfNotConnectedNodeTest() 117 | { 118 | const int node = 1; 119 | _adjacencyList.AddVertex(node); 120 | const int notConnectedNode = 2; 121 | var isNeigthbour = _adjacencyList.IsNeighbourOf(node, notConnectedNode); 122 | Assert.IsFalse(isNeigthbour, "Two nodes that were connected are shown as connected"); 123 | } 124 | 125 | [TestMethod] 126 | public void IsNeighbourOfConnectedNodeTest() 127 | { 128 | LoadInput(); 129 | const int firstNode = 1; 130 | const int secondNode = 2; 131 | var isNeigthbour = _adjacencyList.IsNeighbourOf(firstNode, secondNode); 132 | Assert.IsTrue(isNeigthbour, "Two nodes that are connected are shown as not connected"); 133 | } 134 | 135 | [TestMethod] 136 | public void GetNeighboursCountEmptyTest() 137 | { 138 | const int node = 1; 139 | _adjacencyList.AddVertex(node); 140 | var neightbours = _adjacencyList.GetNeighbours(node); 141 | const int expectedNumberOfNeighbours = 0; 142 | Assert.AreEqual(expectedNumberOfNeighbours, neightbours.Count, "Number of neighbours different from 0 for a node without edges"); 143 | } 144 | 145 | [TestMethod] 146 | public void GetNeighboursCountTest() 147 | { 148 | LoadInput(); 149 | const int firstNode = 1; 150 | var neightbours = _adjacencyList.GetNeighbours(firstNode); 151 | const int expectedNumberOfNeighbours = 2; 152 | Assert.AreEqual(expectedNumberOfNeighbours, neightbours.Count, "Number of neighbours different from expected"); 153 | } 154 | } 155 | } 156 | --------------------------------------------------------------------------------