├── .build
├── build.ps1
├── docfx.json
├── lib
│ └── Newtonsoft.Json.dll
└── setup.ps1
├── .gitignore
├── .nuget
├── NuGet.Config
├── NuGet.exe
└── NuGet.targets
├── .vscode
├── settings.json
└── tasks.json
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── _config.yml
├── appveyor.yml
├── build.bat
├── docs
├── api
│ ├── Advanced.Algorithms.Binary.BaseConversion.html
│ ├── Advanced.Algorithms.Binary.BitHacks.html
│ ├── Advanced.Algorithms.Binary.DivisionModulus.html
│ ├── Advanced.Algorithms.Binary.Gcd.html
│ ├── Advanced.Algorithms.Binary.IntToBinary.html
│ ├── Advanced.Algorithms.Binary.IsMultipleOfNine.html
│ ├── Advanced.Algorithms.Binary.IsMultipleOfThree.html
│ ├── Advanced.Algorithms.Binary.Logarithm.html
│ ├── Advanced.Algorithms.Binary.NextPowOfTwo.html
│ ├── Advanced.Algorithms.Binary.ToggleCase.html
│ ├── Advanced.Algorithms.Binary.html
│ ├── Advanced.Algorithms.Combinatorics.Combination.html
│ ├── Advanced.Algorithms.Combinatorics.Permutation.html
│ ├── Advanced.Algorithms.Combinatorics.Subset.html
│ ├── Advanced.Algorithms.Combinatorics.html
│ ├── Advanced.Algorithms.Compression.HuffmanCoding-1.html
│ ├── Advanced.Algorithms.Compression.html
│ ├── Advanced.Algorithms.DataStructures.AVLTree-1.html
│ ├── Advanced.Algorithms.DataStructures.ArrayList-1.html
│ ├── Advanced.Algorithms.DataStructures.ArrayListEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.BHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BST-1.html
│ ├── Advanced.Algorithms.DataStructures.BSTBase-1.html
│ ├── Advanced.Algorithms.DataStructures.BSTExtensions.html
│ ├── Advanced.Algorithms.DataStructures.BTree-1.html
│ ├── Advanced.Algorithms.DataStructures.BinaryTree-1.html
│ ├── Advanced.Algorithms.DataStructures.BinaryTreeNode-1.html
│ ├── Advanced.Algorithms.DataStructures.BinomialHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BinomialHeapNode-1.html
│ ├── Advanced.Algorithms.DataStructures.BinomialMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BinomialMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.BloomFilter-1.html
│ ├── Advanced.Algorithms.DataStructures.BpTree-1.html
│ ├── Advanced.Algorithms.DataStructures.BpTreeEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.CircularLinkedList-1.html
│ ├── Advanced.Algorithms.DataStructures.CircularLinkedListEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.CircularLinkedListNode-1.html
│ ├── Advanced.Algorithms.DataStructures.DInterval-1.html
│ ├── Advanced.Algorithms.DataStructures.DIntervalTree-1.html
│ ├── Advanced.Algorithms.DataStructures.DRangeTree-1.html
│ ├── Advanced.Algorithms.DataStructures.D_aryMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.D_aryMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.DaryHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.DaryMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.DaryMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.Dictionaries.Dictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.Dictionaries.DictionaryType.html
│ ├── Advanced.Algorithms.DataStructures.Dictionaries.SortedDictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.Dictionaries.html
│ ├── Advanced.Algorithms.DataStructures.Dictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.DictionaryNode-2.html
│ ├── Advanced.Algorithms.DataStructures.DictionaryType.html
│ ├── Advanced.Algorithms.DataStructures.DisJointSet-1.html
│ ├── Advanced.Algorithms.DataStructures.DoublyLinkedList-1.html
│ ├── Advanced.Algorithms.DataStructures.DoublyLinkedListEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.DoublyLinkedListNode-1.html
│ ├── Advanced.Algorithms.DataStructures.ExpressionTree-1.html
│ ├── Advanced.Algorithms.DataStructures.FenwickTree-1.html
│ ├── Advanced.Algorithms.DataStructures.FibonacciHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.FibornacciHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.FibornacciHeapNode-1.html
│ ├── Advanced.Algorithms.DataStructures.FibornacciMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.FibornacciMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.ArrayList-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.Dictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.DictionaryType.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.HashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.HashSetType.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.OrderedDictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.OrderedHashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.Queue-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.QueueType.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.SortedDictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.SortedHashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.Stack-1.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.StackType.html
│ ├── Advanced.Algorithms.DataStructures.Foundation.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.DiGraph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.DiGraphVertex-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.Graph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.GraphVertex-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.WeightedDiGraph-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.WeightedDiGraphVertex-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.WeightedGraph-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.WeightedGraphVertex-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyList.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.DiGraph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.Graph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.WeightedDiGraph-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.WeightedGraph-2.html
│ ├── Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IDiEdge-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IDiGraph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IDiGraphVertex-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IEdge-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IGraph-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.IGraphVertex-1.html
│ ├── Advanced.Algorithms.DataStructures.Graph.html
│ ├── Advanced.Algorithms.DataStructures.HashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.HashSetNode-1.html
│ ├── Advanced.Algorithms.DataStructures.HashSetType.html
│ ├── Advanced.Algorithms.DataStructures.HashSets.HashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.HashSets.HashSetNode-1.html
│ ├── Advanced.Algorithms.DataStructures.HashSets.HashSetType.html
│ ├── Advanced.Algorithms.DataStructures.HashSets.SortedHashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.HashSets.html
│ ├── Advanced.Algorithms.DataStructures.IBSTNode-1.html
│ ├── Advanced.Algorithms.DataStructures.IDistanceCalculator-1.html
│ ├── Advanced.Algorithms.DataStructures.Interval-1.html
│ ├── Advanced.Algorithms.DataStructures.IntervalTree-1.html
│ ├── Advanced.Algorithms.DataStructures.KDTree-1.html
│ ├── Advanced.Algorithms.DataStructures.MaxPriorityQueue-1.html
│ ├── Advanced.Algorithms.DataStructures.MinPriorityQueue-1.html
│ ├── Advanced.Algorithms.DataStructures.OpenAddressDictionaryEnumerator-2.html
│ ├── Advanced.Algorithms.DataStructures.OpenAddressHashSetEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.PairingHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.PairingHeapNode-1.html
│ ├── Advanced.Algorithms.DataStructures.PairingMaxHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.PairingMinHeap-1.html
│ ├── Advanced.Algorithms.DataStructures.PriorityQueue-1.html
│ ├── Advanced.Algorithms.DataStructures.QuadTree-1.html
│ ├── Advanced.Algorithms.DataStructures.Queue-1.html
│ ├── Advanced.Algorithms.DataStructures.QueueType.html
│ ├── Advanced.Algorithms.DataStructures.RTree.html
│ ├── Advanced.Algorithms.DataStructures.RangeTree-1.html
│ ├── Advanced.Algorithms.DataStructures.RedBlackTree-1.html
│ ├── Advanced.Algorithms.DataStructures.SegmentTree-1.html
│ ├── Advanced.Algorithms.DataStructures.SeparateChainingDictionaryEnumerator-2.html
│ ├── Advanced.Algorithms.DataStructures.SeparateChainingHashSetEnumerator-1.html
│ ├── Advanced.Algorithms.DataStructures.SinglyLinkedList-1.html
│ ├── Advanced.Algorithms.DataStructures.SinglyLinkedListNode-1.html
│ ├── Advanced.Algorithms.DataStructures.SkipList-1.html
│ ├── Advanced.Algorithms.DataStructures.SortedDictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.SortedHashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.SparseSet.html
│ ├── Advanced.Algorithms.DataStructures.SplayTree-1.html
│ ├── Advanced.Algorithms.DataStructures.Stack-1.html
│ ├── Advanced.Algorithms.DataStructures.StackType.html
│ ├── Advanced.Algorithms.DataStructures.SuffixTree-1.html
│ ├── Advanced.Algorithms.DataStructures.TernarySearchTree-1.html
│ ├── Advanced.Algorithms.DataStructures.TreapTree-1.html
│ ├── Advanced.Algorithms.DataStructures.Tree-1.html
│ ├── Advanced.Algorithms.DataStructures.Tree.QuadTree-1.html
│ ├── Advanced.Algorithms.DataStructures.Tree.html
│ ├── Advanced.Algorithms.DataStructures.TreeDictionary-2.html
│ ├── Advanced.Algorithms.DataStructures.TreeDictionaryNode-2.html
│ ├── Advanced.Algorithms.DataStructures.TreeHashSet-1.html
│ ├── Advanced.Algorithms.DataStructures.TreeNode-1.html
│ ├── Advanced.Algorithms.DataStructures.Trie-1.html
│ ├── Advanced.Algorithms.DataStructures.html
│ ├── Advanced.Algorithms.Distributed.AsyncQueue-1.html
│ ├── Advanced.Algorithms.Distributed.CircularQueue-1.html
│ ├── Advanced.Algorithms.Distributed.ConsistentHash-1.html
│ ├── Advanced.Algorithms.Distributed.LRUCache-2.html
│ ├── Advanced.Algorithms.Distributed.html
│ ├── Advanced.Algorithms.Geometry.BentleyOttmann.html
│ ├── Advanced.Algorithms.Geometry.ClosestPointPair.html
│ ├── Advanced.Algorithms.Geometry.ConvexHull.html
│ ├── Advanced.Algorithms.Geometry.Line.html
│ ├── Advanced.Algorithms.Geometry.LineExtensions.html
│ ├── Advanced.Algorithms.Geometry.LineIntersection.html
│ ├── Advanced.Algorithms.Geometry.Point.html
│ ├── Advanced.Algorithms.Geometry.PointComparer.html
│ ├── Advanced.Algorithms.Geometry.PointInsidePolygon.html
│ ├── Advanced.Algorithms.Geometry.PointRotation.html
│ ├── Advanced.Algorithms.Geometry.Polygon.html
│ ├── Advanced.Algorithms.Geometry.Rectangle.html
│ ├── Advanced.Algorithms.Geometry.RectangleComparer.html
│ ├── Advanced.Algorithms.Geometry.RectangleIntersection.html
│ ├── Advanced.Algorithms.Geometry.html
│ ├── Advanced.Algorithms.Graph.AStarShortestPath-2.html
│ ├── Advanced.Algorithms.Graph.AllPairShortestPathResult-2.html
│ ├── Advanced.Algorithms.Graph.BellmanFordShortestPath-2.html
│ ├── Advanced.Algorithms.Graph.BiDirectional-1.html
│ ├── Advanced.Algorithms.Graph.BiPartiteMatching-1.html
│ ├── Advanced.Algorithms.Graph.BreadthFirst-1.html
│ ├── Advanced.Algorithms.Graph.Bridge-1.html
│ ├── Advanced.Algorithms.Graph.CycleDetector-1.html
│ ├── Advanced.Algorithms.Graph.DepthFirst-1.html
│ ├── Advanced.Algorithms.Graph.DepthFirstTopSort-1.html
│ ├── Advanced.Algorithms.Graph.DijikstraShortestPath-2.html
│ ├── Advanced.Algorithms.Graph.EdmondKarpMaxFlow-2.html
│ ├── Advanced.Algorithms.Graph.FloydWarshallShortestPath-2.html
│ ├── Advanced.Algorithms.Graph.FordFulkersonMaxFlow-2.html
│ ├── Advanced.Algorithms.Graph.HopcroftKarpMatching-1.html
│ ├── Advanced.Algorithms.Graph.IAStarHeuristic-2.html
│ ├── Advanced.Algorithms.Graph.IBiPartiteMatchOperators-1.html
│ ├── Advanced.Algorithms.Graph.IFlowOperators-1.html
│ ├── Advanced.Algorithms.Graph.IJohnsonsShortestPathOperators-2.html
│ ├── Advanced.Algorithms.Graph.IShortestPathOperators-1.html
│ ├── Advanced.Algorithms.Graph.JohnsonsShortestPath-2.html
│ ├── Advanced.Algorithms.Graph.KahnsTopSort-1.html
│ ├── Advanced.Algorithms.Graph.KosarajuStronglyConnected-1.html
│ ├── Advanced.Algorithms.Graph.Kruskals-2.html
│ ├── Advanced.Algorithms.Graph.MColorResult-2.html
│ ├── Advanced.Algorithms.Graph.MColorer-2.html
│ ├── Advanced.Algorithms.Graph.MSTEdge-2.html
│ ├── Advanced.Algorithms.Graph.MatchEdge-1.html
│ ├── Advanced.Algorithms.Graph.MinCut-2.html
│ ├── Advanced.Algorithms.Graph.MinCutEdge-1.html
│ ├── Advanced.Algorithms.Graph.MinVertexCover-1.html
│ ├── Advanced.Algorithms.Graph.Prims-2.html
│ ├── Advanced.Algorithms.Graph.PushRelabelMaxFlow-2.html
│ ├── Advanced.Algorithms.Graph.ShortestPathResult-2.html
│ ├── Advanced.Algorithms.Graph.TarjansArticulationFinder-1.html
│ ├── Advanced.Algorithms.Graph.TarjansBiConnected-1.html
│ ├── Advanced.Algorithms.Graph.TarjansBridgeFinder-1.html
│ ├── Advanced.Algorithms.Graph.TarjansStronglyConnected-1.html
│ ├── Advanced.Algorithms.Graph.TravellingSalesman-2.html
│ ├── Advanced.Algorithms.Graph.TravellingSalesman.html
│ ├── Advanced.Algorithms.Graph.html
│ ├── Advanced.Algorithms.Miscellaneous.MatrixMultiplication.html
│ ├── Advanced.Algorithms.Miscellaneous.html
│ ├── Advanced.Algorithms.Numerical.FastExponentiation.html
│ ├── Advanced.Algorithms.Numerical.KthSmallest-1.html
│ ├── Advanced.Algorithms.Numerical.MedianStream.html
│ ├── Advanced.Algorithms.Numerical.PrimeGenerator.html
│ ├── Advanced.Algorithms.Numerical.PrimeTester.html
│ ├── Advanced.Algorithms.Numerical.html
│ ├── Advanced.Algorithms.Search.BinarySearch.html
│ ├── Advanced.Algorithms.Search.BoyerMoore-1.html
│ ├── Advanced.Algorithms.Search.QuickSelect-1.html
│ ├── Advanced.Algorithms.Search.SearchAlmostSorted.html
│ ├── Advanced.Algorithms.Search.html
│ ├── Advanced.Algorithms.SortDirection.html
│ ├── Advanced.Algorithms.Sorting.BubbleSort-1.html
│ ├── Advanced.Algorithms.Sorting.BucketSort.html
│ ├── Advanced.Algorithms.Sorting.CountingSort.html
│ ├── Advanced.Algorithms.Sorting.HeapSort-1.html
│ ├── Advanced.Algorithms.Sorting.InsertionSort-1.html
│ ├── Advanced.Algorithms.Sorting.MergeSort-1.html
│ ├── Advanced.Algorithms.Sorting.QuickSort-1.html
│ ├── Advanced.Algorithms.Sorting.RadixSort.html
│ ├── Advanced.Algorithms.Sorting.SelectionSort-1.html
│ ├── Advanced.Algorithms.Sorting.ShellSort-1.html
│ ├── Advanced.Algorithms.Sorting.SortAlmostSorted.html
│ ├── Advanced.Algorithms.Sorting.TreeSort-1.html
│ ├── Advanced.Algorithms.Sorting.html
│ ├── Advanced.Algorithms.String.KMP.html
│ ├── Advanced.Algorithms.String.ManachersPalindrome.html
│ ├── Advanced.Algorithms.String.RabinKarp.html
│ ├── Advanced.Algorithms.String.ZAlgorithm.html
│ ├── Advanced.Algorithms.String.html
│ ├── Advanced.Algorithms.html
│ └── toc.html
├── favicon.ico
├── fonts
│ ├── glyphicons-halflings-regular.eot
│ ├── glyphicons-halflings-regular.svg
│ ├── glyphicons-halflings-regular.ttf
│ ├── glyphicons-halflings-regular.woff
│ └── glyphicons-halflings-regular.woff2
├── index.json
├── logo.svg
├── search-stopwords.json
├── styles
│ ├── docfx.css
│ ├── docfx.js
│ ├── docfx.vendor.css
│ ├── docfx.vendor.js
│ ├── lunr.js
│ ├── lunr.min.js
│ ├── main.css
│ ├── main.js
│ └── search-worker.js
└── xrefmap.yml
├── omnisharp.json
├── src
├── Advanced.Algorithms.Docs.sln
├── Advanced.Algorithms.sln
└── Advanced.Algorithms
│ ├── Advanced.Algorithms.csproj
│ ├── Advanced.Algorithms.csproj.DotSettings
│ ├── Advanced.Algorithms.nuspec
│ ├── App.config
│ ├── Binary
│ ├── BaseConversion.cs
│ ├── GCD.cs
│ └── Logarithm.cs
│ ├── Combinatorics
│ ├── Combination.cs
│ ├── Permutation.cs
│ └── Subset.cs
│ ├── Compression
│ └── HuffmanCoding.cs
│ ├── DataStructures
│ ├── Dictionary
│ │ ├── Dictionary.cs
│ │ ├── OpenAddressDictionary.cs
│ │ ├── OrderedDictionary.cs
│ │ └── SeparateChainingDictionary.cs
│ ├── Graph
│ │ ├── AdjacencyList
│ │ │ ├── DiGraph.cs
│ │ │ ├── Graph.cs
│ │ │ ├── WeightedDiGraph.cs
│ │ │ └── WeightedGraph.cs
│ │ ├── AdjacencyMatrix
│ │ │ ├── DiGraph.cs
│ │ │ ├── Graph.cs
│ │ │ ├── WeightedDiGraph.cs
│ │ │ └── WeightedGraph.cs
│ │ ├── IDiGraph.cs
│ │ └── IGraph.cs
│ ├── HashSet
│ │ ├── HashSet.cs
│ │ ├── OpenAddressHashSet.cs
│ │ ├── OrderedHashSet.cs
│ │ └── SeparateChainingHashSet.cs
│ ├── Heap
│ │ ├── BHeap.cs
│ │ ├── BinomialHeap.cs
│ │ ├── FibonacciHeap.cs
│ │ ├── PairingHeap.cs
│ │ ├── Shared
│ │ │ ├── BinomialHeapNode.cs
│ │ │ ├── FibornacciHeapNode.cs
│ │ │ └── PairingHeapNode.cs
│ │ └── d-aryHeap.cs
│ ├── LinkedList
│ │ ├── CircularLinkedList.cs
│ │ ├── DoublyLinkedList.cs
│ │ └── SinglyLinkedList.cs
│ ├── List
│ │ ├── ArrayList.cs
│ │ └── SkipList.cs
│ ├── Queues
│ │ ├── ArrayQueue.cs
│ │ ├── LinkedListQueue.cs
│ │ ├── PriorityQueue.cs
│ │ └── Queue.cs
│ ├── Set
│ │ ├── BloomFilter.cs
│ │ ├── DisJointSet.cs
│ │ └── SparseSet.cs
│ ├── Shared
│ │ └── IEnumerableExtensions.cs
│ ├── Stack
│ │ ├── ArrayStack.cs
│ │ ├── LinkedListStack.cs
│ │ └── Stack.cs
│ └── Tree
│ │ ├── AvlTree.cs
│ │ ├── B+Tree.cs
│ │ ├── BST.cs
│ │ ├── BTree.cs
│ │ ├── BinaryTree.cs
│ │ ├── FenwickTree.cs
│ │ ├── IntervalTree.cs
│ │ ├── K_DTree.cs
│ │ ├── QuadTree.cs
│ │ ├── RTree.cs
│ │ ├── RangeTree.cs
│ │ ├── RedBlackTree.cs
│ │ ├── SegmentTree.cs
│ │ ├── Shared
│ │ ├── ArrayComparer.cs
│ │ ├── BSTEnumerator.cs
│ │ ├── BSTExtensions.cs
│ │ ├── BSTHelpers.cs
│ │ └── BSTNodeBase.cs
│ │ ├── SplayTree.cs
│ │ ├── SuffixTree.cs
│ │ ├── TernarySearchTree.cs
│ │ ├── TreapTree.cs
│ │ ├── Tree.cs
│ │ └── Trie.cs
│ ├── Distributed
│ ├── AsyncQueue.cs
│ ├── CircularQueue.cs
│ ├── ConsistentHash.cs
│ └── LRUCache.cs
│ ├── Geometry
│ ├── BentleyOttmann.cs
│ ├── ClosestPointPair.cs
│ ├── ConvexHull.cs
│ ├── LineIntersection.cs
│ ├── PointInsidePolygon.cs
│ ├── PointRotation.cs
│ ├── RectangleIntersection.cs
│ ├── Shapes
│ │ ├── Line.cs
│ │ ├── Point.cs
│ │ ├── Polygon.cs
│ │ └── Rectangle.cs
│ └── Shared
│ │ ├── DoubleExtensions.cs
│ │ ├── PointComparer.cs
│ │ └── RectangleComparer.cs
│ ├── Graph
│ ├── ArticulationPoint
│ │ └── TarjansArticulationFinder.cs
│ ├── Bridge
│ │ └── TarjansBridgeFinder.cs
│ ├── Coloring
│ │ └── MColorer.cs
│ ├── Connectivity
│ │ ├── KosarajuStronglyConnected.cs
│ │ ├── TarjansBiConnected.cs
│ │ └── TarjansStronglyConnected.cs
│ ├── Cover
│ │ └── MinVertexCover.cs
│ ├── Cut
│ │ └── MinimumCut.cs
│ ├── Cycle
│ │ └── CycleDetection.cs
│ ├── Flow
│ │ ├── EdmondsKarp.cs
│ │ ├── FordFulkerson.cs
│ │ └── PushRelabel.cs
│ ├── Matching
│ │ ├── BiPartiteMatching.cs
│ │ └── HopcroftKarp.cs
│ ├── MinimumSpanningTree
│ │ ├── Kruskals.cs
│ │ └── Prims.cs
│ ├── Search
│ │ ├── BiDirectional.cs
│ │ ├── BreadthFirst.cs
│ │ └── DepthFirst.cs
│ ├── ShortestPath
│ │ ├── AStar.cs
│ │ ├── Bellman-Ford.cs
│ │ ├── Dijikstra.cs
│ │ ├── Floyd-Warshall.cs
│ │ ├── Johnsons.cs
│ │ └── TravellingSalesman.cs
│ └── Sort
│ │ ├── DepthFirstTopSort.cs
│ │ └── KahnTopSort.cs
│ ├── Numerical
│ ├── Exponentiation.cs
│ ├── PrimeGenerator.cs
│ └── PrimeTester.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── Search
│ ├── BinarySearch.cs
│ ├── BoyerMoore.cs
│ └── QuickSelect.cs
│ ├── Shared
│ ├── CustomComparer.cs
│ └── SortDirection.cs
│ ├── Sorting
│ ├── BubbleSort.cs
│ ├── BucketSort.cs
│ ├── CountingSort.cs
│ ├── HeapSort.cs
│ ├── InsertionSort.cs
│ ├── MergeSort.cs
│ ├── QuickSort.cs
│ ├── RadixSort.cs
│ ├── SelectionSort.cs
│ ├── ShellSort.cs
│ └── TreeSort.cs
│ ├── String
│ ├── ManachersPalindrome.cs
│ └── Search
│ │ ├── KMP.cs
│ │ ├── RabinKarp.cs
│ │ └── ZAlgorithm.cs
│ ├── StrongNameKey.snk
│ └── packages.config
└── tests
├── Advanced.Algorithms.Tests
├── Advanced.Algorithms.Tests.Mono.csproj
├── Advanced.Algorithms.Tests.NetCore.csproj
├── Advanced.Algorithms.Tests.csproj
├── Binary
│ ├── BaseConversion_Tests.cs
│ ├── GCD_Tests.cs
│ └── Logarithm_Tests.cs
├── Combinatorics
│ ├── Combination_Tests.cs
│ ├── Permutation_Tests.cs
│ └── Subset_Tests.cs
├── Compression
│ └── HuffmanCoding_Tests.cs
├── DataStructures
│ ├── Dictionary
│ │ ├── Dictionary_Tests.cs
│ │ └── OrderedDictionary_Tests.cs
│ ├── Graph
│ │ ├── AdjacencyList
│ │ │ ├── DiGraph_Tests.cs
│ │ │ ├── Graph_Tests.cs
│ │ │ ├── WeightedDiGraph_Tests.cs
│ │ │ └── WeightedGraph_Tests.cs
│ │ └── AdjacencyMatrix
│ │ │ ├── DiGraph_Tests.cs
│ │ │ ├── Graph_Tests.cs
│ │ │ ├── WeightedDiGraph_Tests.cs
│ │ │ └── WeightedGraph_Tests.cs
│ ├── HashSet
│ │ ├── HashSet_Tests.cs
│ │ └── OrderedHashSet_Tests.cs
│ ├── Heap
│ │ ├── BHeap_Tests.cs
│ │ ├── BinomialHeap_Tests.cs
│ │ ├── D-aryHeap_Tests.cs
│ │ ├── FibonacciHeap_Tests.cs
│ │ └── PairingHeap_Tests.cs
│ ├── LinkedList
│ │ ├── CircularLinkedList_Tests.cs
│ │ ├── DoublyLinkedList_Tests.cs
│ │ └── SinglyLinkedList_Tests.cs
│ ├── Lists
│ │ ├── ArrayList_Tests.cs
│ │ └── SkipList_Tests.cs
│ ├── Queues
│ │ ├── PriorityQueue_Tests.cs
│ │ └── Queue_Tests.cs
│ ├── Set
│ │ ├── BloomFilter_Tests.cs
│ │ ├── DisJointSet_Tests.cs
│ │ └── SparseSet_Tests.cs
│ ├── Stack_Tests.cs
│ └── Tree
│ │ ├── AVLTree_Tests.cs
│ │ ├── B+Tree_Tests.cs
│ │ ├── BST_Tests.cs
│ │ ├── BTree_Tests.cs
│ │ ├── BinaryTree_Tests.cs
│ │ ├── FenwickTree_Tests.cs
│ │ ├── IntervalTree_Tests.cs
│ │ ├── KdTree_Tests.cs
│ │ ├── QuadTree_Tests.cs
│ │ ├── RTree_Tests.cs
│ │ ├── RangeTreeTests.cs
│ │ ├── RedBlackTree_Tests.cs
│ │ ├── SegmentTree_Tests.cs
│ │ ├── SplayTree_Tests.cs
│ │ ├── SuffixTree_Tests.cs
│ │ ├── TernarySearchTree_Tests.cs
│ │ ├── TestHelpers
│ │ ├── BSTTester.cs
│ │ └── BTreeTester.cs
│ │ ├── TreapTree_Tests.cs
│ │ ├── Tree_Tests.cs
│ │ └── Trie_Tests.cs
├── Distributed
│ ├── AsyncQueue_Tests.cs
│ ├── CircularQueue_Tests.cs
│ ├── ConsistentHash_Tests.cs
│ └── LRUCache_Tests.cs
├── Geometry
│ ├── BentleyOttmann_Tests.cs
│ ├── ClosestPointPair_Tests.cs
│ ├── ConvexHull_Tests.cs
│ ├── LineIntersection_Tests.cs
│ ├── PointInsidePolygon_Tests.cs
│ ├── PointRotation_Tests.cs
│ └── RectangleIntersection_Tests.cs
├── Graph
│ ├── ArticulationPoints
│ │ └── TarjansArticulation_Tests.cs
│ ├── Bridge
│ │ └── TarjansBridge_Tests.cs
│ ├── Coloring
│ │ └── MColoring_Tests.cs
│ ├── Connectivity
│ │ ├── KosarajuStronglyConnected_Tests.cs
│ │ ├── TarjansBiConnected_Tests.cs
│ │ └── TarjansStronglyConnected_Tests.cs
│ ├── Cover
│ │ └── MinVertexCover.cs
│ ├── Cut
│ │ └── MinCut_Tests.cs
│ ├── Cycle
│ │ └── CycleDetection_Tests.cs
│ ├── Flow
│ │ ├── EdmondsKarp_Tests.cs
│ │ ├── FordFulkerson_Tests.cs
│ │ └── PushRelabel_Tests.cs
│ ├── Matching
│ │ ├── BiPartiteMatching_Tests.cs
│ │ └── HopcroftKarp_Tests.cs
│ ├── MinimumSpanningTree
│ │ ├── Kruskals_Test.cs
│ │ └── Prims_Test.cs
│ ├── Search
│ │ ├── BiDirectional_Tests.cs
│ │ ├── BreadthFirst_Tests.cs
│ │ └── DepthFirst_Tests.cs
│ ├── ShortestPath
│ │ ├── AStar_Tests.cs
│ │ ├── BellmanFord_Tests.cs
│ │ ├── Dijikstras_Tests.cs
│ │ ├── FloydWarshall_Tests.cs
│ │ ├── Johnson_Tests.cs
│ │ └── TravellingSalesman_Tests.cs
│ └── Sort
│ │ ├── DepthFirstTopSort_Tests.cs
│ │ └── KahnTopSort_Tests.cs
├── Numerical
│ ├── Exponentiation_Tests.cs
│ ├── Primality_Tests.cs
│ └── PrimeGenerator_Tests.cs
├── Properties
│ └── AssemblyInfo.cs
├── Search
│ ├── BinarySearch_Tests.cs
│ ├── BoyerMoore_Tests.cs
│ └── QuickSelect_Tests.cs
├── Sorting
│ ├── BubbleSort_Tests.cs
│ ├── BucketSort_Tests.cs
│ ├── CountingSort_Tests.cs
│ ├── HeapSort_Tests.cs
│ ├── InsertionSort_Tests.cs
│ ├── MergeSort_Tests.cs
│ ├── QuickSort_Tests.cs
│ ├── RadixSort_Tests.cs
│ ├── SelectionSort_Tests.cs
│ ├── ShellSort_Tests.cs
│ └── TreeSort_Tests.cs
├── String
│ ├── Manachers_Tests.cs
│ └── Search
│ │ ├── KMP_Tests.cs
│ │ ├── RabinKarp_Tests.cs
│ │ └── Z_Tests.cs
└── StrongNameKey.snk
└── escape.txt
/.build/docfx.json:
--------------------------------------------------------------------------------
1 | {
2 | "metadata": [
3 | {
4 | "src": [
5 | {
6 | "files": [ "Advanced.Algorithms.Docs.sln"],
7 | "src": "../src/"
8 | }
9 | ],
10 | "dest": "obj/api"
11 | }
12 | ],
13 | "build": {
14 | "content": [
15 | {
16 | "files": [ "**/*.yml" ],
17 | "src": "obj/api",
18 | "dest": "api"
19 | },
20 | {
21 | "files": [ "*.md" ]
22 | }
23 | ],
24 | "resource": [
25 | {
26 | "files": [ ""]
27 | }
28 | ],
29 | "overwrite": "specs/*.md",
30 | "globalMetadata": {
31 | "_appTitle": "Advanced Algorithms",
32 | "_enableSearch": true
33 | },
34 | "dest": "../docs",
35 | "xrefService": [ "https://xref.docs.microsoft.com/query?uid={uid}" ]
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/.build/lib/Newtonsoft.Json.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/.build/lib/Newtonsoft.Json.dll
--------------------------------------------------------------------------------
/.build/setup.ps1:
--------------------------------------------------------------------------------
1 | param (
2 | [string]$Action="default",
3 | [hashtable]$properties=@{},
4 | [switch]$Help
5 | )
6 |
7 | function Install-Chocolatey()
8 | {
9 | if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall\*"))
10 | {
11 | Write-Output "Chocolatey Not Found, Installing..."
12 | iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))
13 | }
14 | $env:Path += ";${env:ChocolateyInstall}"
15 | }
16 |
17 | function Install-Psake()
18 | {
19 | if(!(Test-Path $env:ChocolateyInstall\lib\Psake\tools\Psake*))
20 | {
21 | choco install psake -y
22 | }
23 | }
24 |
25 | function Install-Git()
26 | {
27 | if(!((Test-Path ${env:ProgramFiles(x86)}\Git*) -Or (Test-Path ${env:ProgramFiles}\Git*)))
28 | {
29 | choco install git.install
30 | }
31 | $env:Path += ";${env:ProgramFiles(x86)}\Git"
32 | $env:Path += ";${env:ProgramFiles}\Git"
33 | }
34 |
35 | function Install-DocFx()
36 | {
37 | if(!(Test-Path $env:ChocolateyInstall\lib\docfx\tools*))
38 | {
39 | choco install docfx --version 2.55
40 | }
41 | $env:Path += ";$env:ChocolateyInstall\lib\docfx\tools"
42 | }
43 |
44 | #current directory
45 | $Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
46 |
47 | $ErrorActionPreference = 'Stop'
48 | Set-StrictMode -Version Latest
49 |
50 | $ScriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
51 | $SolutionRoot = Split-Path -Parent $ScriptPath
52 | $ToolsPath = Join-Path -Path $SolutionRoot -ChildPath "lib"
53 |
54 | if(-not $env:ChocolateyInstall)
55 | {
56 | $env:ChocolateyInstall = "${env:ALLUSERSPROFILE}\chocolatey";
57 | }
58 |
59 | Install-Chocolatey
60 |
61 | Install-Psake
62 |
63 | Install-Git
64 |
65 | Install-DocFx
66 |
67 | $psakeDirectory = (Resolve-Path $env:ChocolateyInstall\lib\Psake*)
68 |
69 | #appveyor for some reason have different location for psake (it has older psake version?)
70 | if(Test-Path $psakeDirectory\tools\Psake\Psake.psm*)
71 | {
72 | Import-Module (Join-Path $psakeDirectory "tools\Psake\Psake.psm1")
73 | }
74 | else
75 | {
76 | Import-Module (Join-Path $psakeDirectory "tools\Psake.psm1")
77 | }
78 |
79 |
80 | #invoke the task
81 | Invoke-Psake -buildFile "$Here\build.ps1" -parameters $properties -tasklist $Action
82 |
--------------------------------------------------------------------------------
/.nuget/NuGet.Config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.nuget/NuGet.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/.nuget/NuGet.exe
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | // The following will hide the js and map files in the editor
3 | "files.exclude": {
4 | "**/.build": true,
5 | "**/.nuget": true,
6 | "**/.vs": true,
7 | "**/docs": true,
8 | "**/packages": true,
9 | "**/bin": true,
10 | "**/obj": true,
11 | "**/*.DotSettings": true,
12 | "**/*.sln": true,
13 | "**/*.Mono.csproj": true,
14 | "**/*.Docs.csproj": true,
15 | "**/*.Algorithms.csproj": true,
16 | "**/*.Tests.csproj": true
17 | },
18 | "search.exclude": {
19 | "**/.build": true,
20 | "**/.nuget": true,
21 | "**/.vs": true,
22 | "**/docs": true,
23 | "**/packages": true,
24 | "**/bin": true,
25 | "**/obj": true,
26 | "**/*.DotSettings": true,
27 | "**/*.sln": true,
28 | "**/*.Mono.csproj": true,
29 | "**/*.Docs.csproj": true,
30 | "**/*.Algorithms.csproj": true,
31 | "**/*.Tests.csproj": true
32 | }
33 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "type": "process",
7 | "command": "dotnet",
8 | "args": ["build","${workspaceFolder}/src/Advanced.Algorithms.NetCore.sln"],
9 | "problemMatcher": "$msCompile",
10 | "group": {
11 | "kind": "build",
12 | "isDefault": true
13 | }
14 | }
15 | ]
16 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Jehonathan
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | - [ ] This is not a new algorithm. See readme.
2 | Doneness:
3 | - [ ] Build is okay - I made sure that this change is building successfully.
4 | - [ ] No Bugs - I made sure that this change is working properly as expected. It doesn't have any bugs that you are aware of.
5 | - [ ] Branching - If this is not a hotfix, I am making this request against develop branch
6 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | baseurl: /Advanced-Algorithms
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | # AppVeyor CI build file
2 |
3 | # Notes:
4 | # - Minimal appveyor.yml file is an empty file. All sections are optional.
5 | # - Indent each level of configuration with 2 spaces. Do not use tabs!
6 | # - All section names are case-sensitive.
7 | # - Section names should be unique on each level.
8 |
9 | # version format
10 | version: 0.0.{build}
11 | image: Visual Studio 2017
12 |
13 | shallow_clone: true
14 |
15 | #---------------------------------#
16 | # build configuration #
17 | #---------------------------------#
18 |
19 | # build platform, i.e. x86, x64, Any CPU. This setting is optional.
20 | platform: Any CPU
21 |
22 | # build Configuration, i.e. Debug, Release, etc.
23 | configuration: Release
24 |
25 | # to run your custom scripts instead of automatic MSBuild
26 | build_script:
27 | - cmd: build.bat Package
28 |
29 | assembly_info:
30 | patch: true
31 | file: AssemblyInfo.*
32 | assembly_version: "{version}"
33 | assembly_file_version: "{version}"
34 | assembly_informational_version: "{version}"
35 |
36 | # to disable automatic tests
37 | test: on
38 |
39 | # skip building commits that add tags (such as release tag)
40 | skip_tags: true
41 |
42 | skip_commits:
43 | author: buildbot171
44 | files:
45 | - docs/*
46 | - README.md
47 | - LICENSE
48 |
49 | #---------------------------------#
50 | # artifacts configuration #
51 | #---------------------------------#
52 |
53 | nuget:
54 | disable_publish_on_pr: true # disable publishing of .nupkg artifacts to account/project feeds for pull request builds
55 |
56 | artifacts:
57 | - path: '**\Advanced.Algorithms.*.nupkg'
58 |
59 | environment:
60 | github_access_token:
61 | secure: mZLeq0GTB9kb5b6+HnVpJB6hhiYMJIQ2+Zf/DwZ/LEIyxJaYB1nx36aGHXE9q1cN
62 | github_email:
63 | secure: iBJZGqxyiHVNeYI0uIW+MdGd3I3pg8brJtETNRkKe/A=
64 | nuget_access_token:
65 | secure: OO7/GRKfrScfh1Z92UxFEuBuXUM0WlPv2RMzCL6WnYAMByhiyWC2e1ezy34r/Lc6
66 | deploy:
67 | - provider: GitHub
68 | auth_token: $(github_access_token)
69 | on:
70 | branch: /(stable|beta)/
71 | - provider: NuGet
72 | api_key: $(nuget_access_token)
73 | on:
74 | branch: /(stable|beta)/
75 |
--------------------------------------------------------------------------------
/build.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | powershell -NoProfile -ExecutionPolicy bypass -Command "%~dp0.build\setup.ps1 %*; if ($psake.build_success -eq $false) { exit 1 } else { exit 0 }"
4 | exit /B %errorlevel%
--------------------------------------------------------------------------------
/docs/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/favicon.ico
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/fonts/glyphicons-halflings-regular.eot
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/fonts/glyphicons-halflings-regular.ttf
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/fonts/glyphicons-halflings-regular.woff
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/fonts/glyphicons-halflings-regular.woff2
--------------------------------------------------------------------------------
/docs/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
4 |
26 |
--------------------------------------------------------------------------------
/docs/search-stopwords.json:
--------------------------------------------------------------------------------
1 | [
2 | "a",
3 | "able",
4 | "about",
5 | "across",
6 | "after",
7 | "all",
8 | "almost",
9 | "also",
10 | "am",
11 | "among",
12 | "an",
13 | "and",
14 | "any",
15 | "are",
16 | "as",
17 | "at",
18 | "be",
19 | "because",
20 | "been",
21 | "but",
22 | "by",
23 | "can",
24 | "cannot",
25 | "could",
26 | "dear",
27 | "did",
28 | "do",
29 | "does",
30 | "either",
31 | "else",
32 | "ever",
33 | "every",
34 | "for",
35 | "from",
36 | "get",
37 | "got",
38 | "had",
39 | "has",
40 | "have",
41 | "he",
42 | "her",
43 | "hers",
44 | "him",
45 | "his",
46 | "how",
47 | "however",
48 | "i",
49 | "if",
50 | "in",
51 | "into",
52 | "is",
53 | "it",
54 | "its",
55 | "just",
56 | "least",
57 | "let",
58 | "like",
59 | "likely",
60 | "may",
61 | "me",
62 | "might",
63 | "most",
64 | "must",
65 | "my",
66 | "neither",
67 | "no",
68 | "nor",
69 | "not",
70 | "of",
71 | "off",
72 | "often",
73 | "on",
74 | "only",
75 | "or",
76 | "other",
77 | "our",
78 | "own",
79 | "rather",
80 | "said",
81 | "say",
82 | "says",
83 | "she",
84 | "should",
85 | "since",
86 | "so",
87 | "some",
88 | "than",
89 | "that",
90 | "the",
91 | "their",
92 | "them",
93 | "then",
94 | "there",
95 | "these",
96 | "they",
97 | "this",
98 | "tis",
99 | "to",
100 | "too",
101 | "twas",
102 | "us",
103 | "wants",
104 | "was",
105 | "we",
106 | "were",
107 | "what",
108 | "when",
109 | "where",
110 | "which",
111 | "while",
112 | "who",
113 | "whom",
114 | "why",
115 | "will",
116 | "with",
117 | "would",
118 | "yet",
119 | "you",
120 | "your"
121 | ]
122 |
--------------------------------------------------------------------------------
/docs/styles/main.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/docs/styles/main.css
--------------------------------------------------------------------------------
/docs/styles/main.js:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.
2 |
--------------------------------------------------------------------------------
/docs/styles/search-worker.js:
--------------------------------------------------------------------------------
1 | (function () {
2 | importScripts('lunr.min.js');
3 |
4 | var lunrIndex;
5 |
6 | var stopWords = null;
7 | var searchData = {};
8 |
9 | lunr.tokenizer.separator = /[\s\-\.\(\)]+/;
10 |
11 | var stopWordsRequest = new XMLHttpRequest();
12 | stopWordsRequest.open('GET', '../search-stopwords.json');
13 | stopWordsRequest.onload = function () {
14 | if (this.status != 200) {
15 | return;
16 | }
17 | stopWords = JSON.parse(this.responseText);
18 | buildIndex();
19 | }
20 | stopWordsRequest.send();
21 |
22 | var searchDataRequest = new XMLHttpRequest();
23 |
24 | searchDataRequest.open('GET', '../index.json');
25 | searchDataRequest.onload = function () {
26 | if (this.status != 200) {
27 | return;
28 | }
29 | searchData = JSON.parse(this.responseText);
30 |
31 | buildIndex();
32 |
33 | postMessage({ e: 'index-ready' });
34 | }
35 | searchDataRequest.send();
36 |
37 | onmessage = function (oEvent) {
38 | var q = oEvent.data.q;
39 | var hits = lunrIndex.search(q);
40 | var results = [];
41 | hits.forEach(function (hit) {
42 | var item = searchData[hit.ref];
43 | results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords });
44 | });
45 | postMessage({ e: 'query-ready', q: q, d: results });
46 | }
47 |
48 | function buildIndex() {
49 | if (stopWords !== null && !isEmpty(searchData)) {
50 | lunrIndex = lunr(function () {
51 | this.pipeline.remove(lunr.stopWordFilter);
52 | this.ref('href');
53 | this.field('title', { boost: 50 });
54 | this.field('keywords', { boost: 20 });
55 |
56 | for (var prop in searchData) {
57 | if (searchData.hasOwnProperty(prop)) {
58 | this.add(searchData[prop]);
59 | }
60 | }
61 |
62 | var docfxStopWordFilter = lunr.generateStopWordFilter(stopWords);
63 | lunr.Pipeline.registerFunction(docfxStopWordFilter, 'docfxStopWordFilter');
64 | this.pipeline.add(docfxStopWordFilter);
65 | this.searchPipeline.add(docfxStopWordFilter);
66 | });
67 | }
68 | }
69 |
70 | function isEmpty(obj) {
71 | if(!obj) return true;
72 |
73 | for (var prop in obj) {
74 | if (obj.hasOwnProperty(prop))
75 | return false;
76 | }
77 |
78 | return true;
79 | }
80 | })();
81 |
--------------------------------------------------------------------------------
/omnisharp.json:
--------------------------------------------------------------------------------
1 | {
2 | "fileOptions": {
3 | "excludeSearchPatterns": [
4 | "**/*.Docs.csproj",
5 | "**/*.DotSettings",
6 | "**/*.sln",
7 | "**/*.Mono.csproj",
8 | "**/*.Docs.csproj",
9 | "**/*.Algorithms.csproj",
10 | "**/*.Tests.csproj"
11 | ]
12 | }
13 | }
--------------------------------------------------------------------------------
/src/Advanced.Algorithms.Docs.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30621.155
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Advanced.Algorithms", "Advanced.Algorithms\Advanced.Algorithms.csproj", "{C0BE46BB-2E54-43D2-953D-728D9B96B52A}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {C0BE46BB-2E54-43D2-953D-728D9B96B52A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {C0BE46BB-2E54-43D2-953D-728D9B96B52A}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {C0BE46BB-2E54-43D2-953D-728D9B96B52A}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {C0BE46BB-2E54-43D2-953D-728D9B96B52A}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {A250E1E5-3ABA-4FED-9A0E-6C63EB0261E0}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Advanced.Algorithms.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net45;netstandard1.0
5 | Advanced.Algorithms
6 | false
7 | True
8 | StrongNameKey.snk
9 | False
10 | True
11 | latest
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Advanced.Algorithms.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Advanced.Algorithms
5 | $version$
6 | Advanced Algorithms
7 | Advanced Algorithms GitHub contributors
8 | justcoding121
9 | https://github.com/justcoding121/Advanced-Algorithms/blob/develop/LICENSE
10 | https://github.com/justcoding121/Advanced-Algorithms
11 | false
12 | 100+ algorithms and datastructures.
13 |
14 | Copyright © justcoding121. All rights reserved.
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Binary/GCD.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Binary
2 | {
3 | ///
4 | /// GCD without division or mod operators but using substraction.
5 | ///
6 | public class Gcd
7 | {
8 | public static int Find(int a, int b)
9 | {
10 | if (b == 0)
11 | {
12 | return a;
13 | }
14 |
15 | if (a == 0)
16 | {
17 | return b;
18 | }
19 |
20 | //fix negative numbers
21 | if (a < 0)
22 | {
23 | a = -a;
24 | }
25 |
26 | if (b < 0)
27 | {
28 | b = -b;
29 | }
30 |
31 | // p and q even
32 | if ((a & 1) == 0 && (b & 1) == 0)
33 | {
34 | //divide both a and b by 2
35 | //multiply by 2 the result
36 | return Find(a >> 1, b >> 1) << 1;
37 | }
38 |
39 | // a is even, b is odd
40 |
41 | if ((a & 1) == 0)
42 | {
43 | //divide a by 2
44 | return Find(a >> 1, b);
45 | }
46 |
47 | // a is odd, b is even
48 | if ((b & 1) == 0)
49 | {
50 | //divide by by 2
51 | return Find(a, b >> 1);
52 | }
53 | // a and b odd, a >= b
54 |
55 | if (a >= b)
56 | {
57 | //since substracting two odd numbers gives an even number
58 | //divide (a-b) by 2 to reduce calculations
59 | return Find((a - b) >> 1, b);
60 | }
61 | // a and b odd, a < b
62 |
63 | //since substracting two odd numbers gives an even number
64 | //divide (b-a) by 2 to reduce calculations
65 | return Find(a, (b - a) >> 1);
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Binary/Logarithm.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Binary
2 | {
3 | ///
4 | /// Logarithm calculator.
5 | ///
6 | public class Logarithm
7 | {
8 | public static int CalcBase2LogFloor(int x)
9 | {
10 | //make all right most bits after MSB to 1s
11 | //for example make ..001000 => ..001111
12 | x = x | (x >> 1);
13 | x = x | (x >> 2);
14 | x = x | (x >> 4);
15 | x = x | (x >> 8);
16 | x = x | (x >> 16);
17 |
18 | //now log(x) base 2 = count the number of set bits - 1
19 | //to find the count do the following steps
20 |
21 | //set bit count of 2 bit groups
22 | //0x0555.. will be like 010101010101..
23 | x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
24 |
25 | //set bit count of 4 bit groups
26 | //0x0333.. will be like 001100110011..
27 | x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
28 |
29 | //set bit count of 8 bit groups of 4
30 | //0x0f0f.. will be like 0000111100001111..
31 | x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
32 |
33 | //sum up the four groups of 8 bit
34 | x = (x & 0x000000FF)
35 | + ((x >> 8) & 0x000000FF)
36 | + ((x >> 16) & 0x000000FF)
37 | + ((x >> 24) & 0x000000FF);
38 |
39 | //-1 for log of base 2
40 | return x - 1;
41 |
42 | }
43 |
44 | public static int CalcBase10LogFloor(int x)
45 | {
46 | //using the below relation
47 | //log(x) base b = (log(x) base a) / (log(b) base a)
48 | var n = CalcBase2LogFloor(x);
49 | var d = CalcBase2LogFloor(10);
50 |
51 | return n / d;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Combinatorics/Combination.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Combinatorics
4 | {
5 | ///
6 | /// Combinations computer.
7 | ///
8 | public class Combination
9 | {
10 | public static List> Find(List input, int r, bool withRepetition)
11 | {
12 | var result = new List>();
13 |
14 | recurse(input, r, withRepetition, 0, new List(), new HashSet(), result);
15 |
16 | return result;
17 | }
18 |
19 | private static void recurse(List input, int r, bool withRepetition,
20 | int k, List prefix, HashSet prefixIndices,
21 | List> result)
22 | {
23 | if (prefix.Count == r)
24 | {
25 | result.Add(new List(prefix));
26 | return;
27 | }
28 |
29 | for (int j = k; j < input.Count; j++)
30 | {
31 | if (prefixIndices.Contains(j) && !withRepetition)
32 | {
33 | continue;
34 | }
35 |
36 | prefix.Add(input[j]);
37 | prefixIndices.Add(j);
38 |
39 | recurse(input, r, withRepetition, j, prefix, prefixIndices, result);
40 |
41 | prefix.RemoveAt(prefix.Count - 1);
42 | prefixIndices.Remove(j);
43 | }
44 | }
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Combinatorics/Permutation.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Combinatorics
4 | {
5 | ///
6 | /// Permutation computer.
7 | ///
8 | public class Permutation
9 | {
10 | public static List> Find(List input, int r, bool withRepetition = false)
11 | {
12 | var result = new List>();
13 |
14 | recurse(input, r, withRepetition, new List(), new HashSet(), result);
15 |
16 | return result;
17 | }
18 |
19 | private static void recurse(List input, int r, bool withRepetition,
20 | List prefix, HashSet prefixIndices,
21 | List> result)
22 | {
23 | if (prefix.Count == r)
24 | {
25 | result.Add(new List(prefix));
26 | return;
27 | }
28 |
29 | for (int j = 0; j < input.Count; j++)
30 | {
31 | if (prefixIndices.Contains(j) && !withRepetition)
32 | {
33 | continue;
34 | }
35 |
36 | prefix.Add(input[j]);
37 | prefixIndices.Add(j);
38 |
39 | recurse(input, r, withRepetition, prefix, prefixIndices, result);
40 |
41 | prefix.RemoveAt(prefix.Count - 1);
42 | prefixIndices.Remove(j);
43 | }
44 | }
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Combinatorics/Subset.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Combinatorics
4 | {
5 | ///
6 | /// Subset computer.
7 | ///
8 | public class Subset
9 | {
10 | public static List> Find(List input)
11 | {
12 | var result = new List>();
13 |
14 | recurse(input, 0, new List(), new HashSet(), result);
15 |
16 | return result;
17 | }
18 |
19 | private static void recurse(List input,
20 | int k, List prefix, HashSet prefixIndices,
21 | List> result)
22 | {
23 | result.Add(new List(prefix));
24 |
25 | for (int j = k; j < input.Count; j++)
26 | {
27 | if (prefixIndices.Contains(j))
28 | {
29 | continue;
30 | }
31 |
32 | prefix.Add(input[j]);
33 | prefixIndices.Add(j);
34 |
35 | recurse(input, j, prefix, prefixIndices, result);
36 |
37 | prefix.RemoveAt(prefix.Count - 1);
38 | prefixIndices.Remove(j);
39 | }
40 | }
41 |
42 |
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Graph/IDiGraph.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Graph
5 | {
6 | ///
7 | /// Directed graph.
8 | ///
9 | ///
10 | public interface IDiGraph
11 | {
12 | bool IsWeightedGraph { get; }
13 |
14 | bool ContainsVertex(T value);
15 | IDiGraphVertex GetVertex(T key);
16 | IDiGraphVertex ReferenceVertex { get; }
17 | IEnumerable> VerticesAsEnumberable { get; }
18 | int VerticesCount { get; }
19 |
20 | bool HasEdge(T source, T destination);
21 |
22 | IDiGraph Clone();
23 | }
24 |
25 | public interface IDiGraphVertex
26 | {
27 | T Key { get; }
28 | IEnumerable> OutEdges { get; }
29 | IEnumerable> InEdges { get; }
30 |
31 | IDiEdge GetOutEdge(IDiGraphVertex targetVertex);
32 |
33 | int OutEdgeCount { get; }
34 | int InEdgeCount { get; }
35 | }
36 |
37 | public interface IDiEdge
38 | {
39 | W Weight() where W : IComparable;
40 | T TargetVertexKey { get; }
41 | IDiGraphVertex TargetVertex { get; }
42 | }
43 |
44 | internal class DiEdge : IDiEdge where C : IComparable
45 | {
46 | private object weight;
47 |
48 | internal DiEdge(IDiGraphVertex target, C weight)
49 | {
50 | TargetVertex = target;
51 | this.weight = weight;
52 | }
53 |
54 | public T TargetVertexKey => TargetVertex.Key;
55 |
56 | public IDiGraphVertex TargetVertex { get; private set; }
57 |
58 | public W Weight() where W : IComparable
59 | {
60 | return (W)weight;
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Graph/IGraph.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Graph
5 | {
6 | ///
7 | /// UnDirected graph. (When implemented on a directed graphs only outgoing edges are considered as Edges).
8 | ///
9 | ///
10 | public interface IGraph
11 | {
12 | bool IsWeightedGraph { get; }
13 |
14 | int VerticesCount { get; }
15 | IGraphVertex ReferenceVertex { get; }
16 | bool ContainsVertex(T key);
17 | IGraphVertex GetVertex(T key);
18 | IEnumerable> VerticesAsEnumberable { get; }
19 |
20 | bool HasEdge(T source, T destination);
21 |
22 | IGraph Clone();
23 | }
24 |
25 | public interface IGraphVertex
26 | {
27 | T Key { get; }
28 | IEnumerable> Edges { get; }
29 |
30 | IEdge GetEdge(IGraphVertex targetVertex);
31 | }
32 |
33 | public interface IEdge
34 | {
35 | W Weight() where W : IComparable;
36 | T TargetVertexKey { get; }
37 | IGraphVertex TargetVertex { get; }
38 | }
39 |
40 | internal class Edge : IEdge where C : IComparable
41 | {
42 | private object weight;
43 |
44 | internal Edge(IGraphVertex target, C weight)
45 | {
46 | this.TargetVertex = target;
47 | this.weight = weight;
48 | }
49 |
50 | public T TargetVertexKey => TargetVertex.Key;
51 |
52 | public IGraphVertex TargetVertex { get; private set; }
53 |
54 | public W Weight() where W : IComparable
55 | {
56 | return (W)weight;
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Heap/Shared/BinomialHeapNode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures
5 | {
6 | internal class BinomialHeapNode : IComparable where T : IComparable
7 | {
8 | internal T Value { get; set; }
9 | internal int Degree => Children.Count;
10 |
11 | internal BinomialHeapNode Parent { get; set; }
12 | internal List> Children { get; set; }
13 |
14 | internal BinomialHeapNode(T value)
15 | {
16 | this.Value = value;
17 |
18 | Children = new List>();
19 | }
20 |
21 | public int CompareTo(object obj)
22 | {
23 | return Value.CompareTo(((BinomialHeapNode)obj).Value);
24 | }
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Heap/Shared/FibornacciHeapNode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.DataStructures
4 | {
5 | internal class FibonacciHeapNode : IComparable where T : IComparable
6 | {
7 | internal T Value { get; set; }
8 |
9 | internal int Degree;
10 | internal FibonacciHeapNode ChildrenHead { get; set; }
11 |
12 | internal FibonacciHeapNode Parent { get; set; }
13 | internal bool LostChild { get; set; }
14 |
15 | internal FibonacciHeapNode Previous;
16 | internal FibonacciHeapNode Next;
17 |
18 | internal FibonacciHeapNode(T value)
19 | {
20 | Value = value;
21 | }
22 |
23 | public int CompareTo(object obj)
24 | {
25 | return Value.CompareTo(((FibonacciHeapNode)obj).Value);
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Heap/Shared/PairingHeapNode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.DataStructures
4 | {
5 | internal class PairingHeapNode : IComparable where T : IComparable
6 | {
7 | internal T Value { get; set; }
8 |
9 | internal PairingHeapNode ChildrenHead { get; set; }
10 | internal bool IsHeadChild => Previous != null && Previous.ChildrenHead == this;
11 |
12 | internal PairingHeapNode(T value)
13 | {
14 | this.Value = value;
15 | }
16 |
17 | internal PairingHeapNode Previous;
18 | internal PairingHeapNode Next;
19 |
20 | public int CompareTo(object obj)
21 | {
22 | return Value.CompareTo(((PairingHeapNode)obj).Value);
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Queues/ArrayQueue.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Foundation
5 | {
6 | internal class ArrayQueue : IQueue
7 | {
8 | private readonly List list = new List();
9 |
10 | public int Count { get; private set; }
11 |
12 | public void Enqueue(T item)
13 | {
14 | list.Insert(0, item);
15 | Count++;
16 | }
17 |
18 | public T Dequeue()
19 | {
20 | if (list.Count == 0)
21 | {
22 | throw new System.Exception("Empty Queue");
23 | }
24 |
25 | var result = list[list.Count - 1];
26 | list.RemoveAt(list.Count - 1);
27 | Count--;
28 | return result;
29 | }
30 |
31 | public IEnumerator GetEnumerator()
32 | {
33 | return GetEnumerator();
34 | }
35 |
36 | IEnumerator IEnumerable.GetEnumerator()
37 | {
38 | return list.GetEnumerator();
39 | }
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Queues/LinkedListQueue.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Foundation
5 | {
6 | internal class LinkedListQueue : IQueue
7 | {
8 | private readonly DoublyLinkedList list = new DoublyLinkedList();
9 |
10 | public int Count { get; private set; }
11 |
12 | public void Enqueue(T item)
13 | {
14 | list.InsertFirst(item);
15 | Count++;
16 | }
17 |
18 | public T Dequeue()
19 | {
20 | if (list.Head == null)
21 | {
22 | throw new System.Exception("Empty Queue");
23 | }
24 |
25 | var result = list.DeleteLast();
26 | Count--;
27 | return result;
28 | }
29 |
30 | public IEnumerator GetEnumerator()
31 | {
32 | return GetEnumerator();
33 | }
34 |
35 | IEnumerator IEnumerable.GetEnumerator()
36 | {
37 | return list.GetEnumerator();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Queues/PriorityQueue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 |
5 | namespace Advanced.Algorithms.DataStructures
6 | {
7 | ///
8 | /// A priority queue implementation using heap
9 | ///
10 | public class PriorityQueue : IEnumerable where T : IComparable
11 | {
12 | private readonly BHeap heap;
13 | public PriorityQueue(SortDirection sortDirection = SortDirection.Ascending)
14 | {
15 | heap = new BHeap(sortDirection);
16 | }
17 |
18 | ///
19 | /// Time complexity:O(log(n)).
20 | ///
21 | public void Enqueue(T item)
22 | {
23 | heap.Insert(item);
24 | }
25 |
26 | ///
27 | /// Time complexity:O(log(n)).
28 | ///
29 | public T Dequeue()
30 | {
31 | return heap.Extract();
32 | }
33 |
34 | ///
35 | /// Time complexity:O(1).
36 | ///
37 | public T Peek()
38 | {
39 | return heap.Peek();
40 | }
41 |
42 | public IEnumerator GetEnumerator()
43 | {
44 | return GetEnumerator();
45 | }
46 |
47 | IEnumerator IEnumerable.GetEnumerator()
48 | {
49 | return heap.GetEnumerator();
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Queues/Queue.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Foundation
5 | {
6 | ///
7 | /// A queue implementation.
8 | ///
9 | public class Queue : IEnumerable
10 | {
11 | private readonly IQueue queue;
12 |
13 | ///
14 | /// The number of items in the queue.
15 | ///
16 | public int Count => queue.Count;
17 |
18 | /// The queue implementation type.
19 | public Queue(QueueType type = QueueType.Array)
20 | {
21 | if (type == QueueType.Array)
22 | {
23 | queue = new ArrayQueue();
24 | }
25 | else
26 | {
27 | queue = new LinkedListQueue();
28 | }
29 | }
30 |
31 | ///
32 | /// Time complexity:O(1).
33 | ///
34 | public void Enqueue(T item)
35 | {
36 | queue.Enqueue(item);
37 | }
38 |
39 | ///
40 | /// Time complexity:O(1).
41 | ///
42 | public T Dequeue()
43 | {
44 | return queue.Dequeue();
45 | }
46 |
47 | public IEnumerator GetEnumerator()
48 | {
49 | return GetEnumerator();
50 | }
51 |
52 | IEnumerator IEnumerable.GetEnumerator()
53 | {
54 | return queue.GetEnumerator();
55 | }
56 | }
57 |
58 | internal interface IQueue : IEnumerable
59 | {
60 | int Count { get; }
61 | void Enqueue(T item);
62 | T Dequeue();
63 | }
64 |
65 | ///
66 | /// The queue implementation types.
67 | ///
68 | public enum QueueType
69 | {
70 | Array = 0,
71 | LinkedList = 1
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Set/BloomFilter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 |
5 | namespace Advanced.Algorithms.DataStructures
6 | {
7 | ///
8 | /// A simple bloom filter implementation.
9 | ///
10 | public class BloomFilter
11 | {
12 | private readonly BitArray filter;
13 |
14 | private readonly int numberOfHashFunctions;
15 |
16 | ///
17 | /// Higher the size lower the collision and
18 | /// failure probablity.
19 | ///
20 | public BloomFilter(int size, int numberOfHashFunctions = 2)
21 | {
22 | if (size <= numberOfHashFunctions)
23 | {
24 | throw new ArgumentException("size cannot be less than or equal to numberOfHashFunctions.");
25 | }
26 |
27 | this.numberOfHashFunctions = numberOfHashFunctions;
28 | filter = new BitArray(size);
29 | }
30 |
31 | ///
32 | /// Time complexity: O(1).
33 | ///
34 | public void AddKey(T key)
35 | {
36 | foreach (var hash in getHashes(key))
37 | {
38 | filter[hash % filter.Length] = true;
39 | }
40 | }
41 |
42 | ///
43 | /// Time complexity: O(1).
44 | ///
45 | public bool KeyExists(T key)
46 | {
47 | foreach (var hash in getHashes(key))
48 | {
49 | if (filter[hash % filter.Length] == false)
50 | {
51 | return false;
52 | }
53 | }
54 |
55 | return true;
56 | }
57 |
58 | private IEnumerable getHashes(T key)
59 | {
60 | for (var i = 1; i <= numberOfHashFunctions; i++)
61 | {
62 | var obj = new { Key = key, InitialValue = i };
63 | yield return Math.Abs(obj.GetHashCode());
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Shared/IEnumerableExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.DataStructures
4 | {
5 | internal static class IEnumerableExtensions
6 | {
7 | internal static IEnumerable AsEnumerable(this IEnumerator e)
8 | {
9 | while (e.MoveNext())
10 | {
11 | yield return e.Current;
12 | }
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Stack/ArrayStack.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 |
5 | namespace Advanced.Algorithms.DataStructures.Foundation
6 | {
7 | internal class ArrayStack : IStack
8 | {
9 | public int Count { get; private set; }
10 |
11 | private readonly List list = new List();
12 |
13 | public T Pop()
14 | {
15 | if (Count == 0)
16 | {
17 | throw new Exception("Empty stack");
18 | }
19 |
20 | var result = list[list.Count - 1];
21 | list.RemoveAt(list.Count - 1);
22 | Count--;
23 | return result;
24 | }
25 |
26 | public void Push(T item)
27 | {
28 | list.Add(item);
29 | Count++;
30 | }
31 |
32 | public T Peek()
33 | {
34 | if (Count == 0)
35 | {
36 | return default(T);
37 | }
38 |
39 | return list[list.Count - 1];
40 | }
41 |
42 | public IEnumerator GetEnumerator()
43 | {
44 | return GetEnumerator();
45 | }
46 |
47 | IEnumerator IEnumerable.GetEnumerator()
48 | {
49 | return list.GetEnumerator();
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Stack/LinkedListStack.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 |
5 | namespace Advanced.Algorithms.DataStructures.Foundation
6 | {
7 | internal class LinkedListStack : IStack
8 | {
9 | public int Count { get; private set; }
10 |
11 | private readonly SinglyLinkedList list = new SinglyLinkedList();
12 |
13 | public T Pop()
14 | {
15 | if (Count == 0)
16 | {
17 | throw new Exception("Empty stack");
18 | }
19 |
20 | var result = list.DeleteFirst();
21 | Count--;
22 | return result;
23 | }
24 |
25 | public void Push(T item)
26 | {
27 | list.InsertFirst(item);
28 | Count++;
29 | }
30 |
31 | public T Peek()
32 | {
33 | return Count == 0 ? default(T) : list.Head.Data;
34 | }
35 |
36 | public IEnumerator GetEnumerator()
37 | {
38 | return GetEnumerator();
39 | }
40 |
41 | IEnumerator IEnumerable.GetEnumerator()
42 | {
43 | return list.GetEnumerator();
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Stack/Stack.cs:
--------------------------------------------------------------------------------
1 | using System.Collections;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.DataStructures.Foundation
5 | {
6 | ///
7 | /// A stack implementation.
8 | ///
9 | public class Stack : IEnumerable
10 | {
11 | private readonly IStack stack;
12 |
13 | ///
14 | /// The total number of items in this stack.
15 | ///
16 | public int Count => stack.Count;
17 |
18 | /// The stack type to use.
19 | public Stack(StackType type = StackType.Array)
20 | {
21 | if (type == StackType.Array)
22 | {
23 | stack = new ArrayStack();
24 | }
25 | else
26 | {
27 | stack = new LinkedListStack();
28 | }
29 | }
30 |
31 | ///
32 | /// Time complexity:O(1).
33 | ///
34 | /// The item popped.
35 | public T Pop()
36 | {
37 | return stack.Pop();
38 | }
39 |
40 | ///
41 | /// Time complexity:O(1).
42 | ///
43 | /// The item to push.
44 | public void Push(T item)
45 | {
46 | stack.Push(item);
47 | }
48 |
49 | ///
50 | /// Peek from stack.
51 | /// Time complexity:O(1).
52 | ///
53 | /// The item peeked.
54 | public T Peek()
55 | {
56 | return stack.Peek();
57 | }
58 |
59 | public IEnumerator GetEnumerator()
60 | {
61 | return GetEnumerator();
62 | }
63 |
64 | IEnumerator IEnumerable.GetEnumerator()
65 | {
66 | return stack.GetEnumerator();
67 | }
68 | }
69 |
70 | internal interface IStack : IEnumerable
71 | {
72 | int Count { get; }
73 | T Pop();
74 | void Push(T item);
75 |
76 | T Peek();
77 | }
78 |
79 | ///
80 | /// The stack implementation types.
81 | ///
82 | public enum StackType
83 | {
84 | Array = 0,
85 | LinkedList = 1
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Tree/Shared/ArrayComparer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.DataStructures
4 | {
5 | ///
6 | /// Compares two arrays.
7 | ///
8 | internal class ArrayComparer : IEqualityComparer
9 | {
10 | public bool Equals(T[] x, T[] y)
11 | {
12 | if (x == y)
13 | {
14 | return true;
15 | }
16 |
17 | for (int i = 0; i < x.Length; i++)
18 | {
19 | if (!x[i].Equals(y[i]))
20 | {
21 | return false;
22 | }
23 | }
24 |
25 | return true;
26 | }
27 |
28 | public int GetHashCode(T[] x)
29 | {
30 | unchecked
31 | {
32 | if (x == null)
33 | {
34 | return 0;
35 | }
36 |
37 | int hash = 17;
38 |
39 | foreach (var element in x)
40 | {
41 | hash = hash * 31 + element.GetHashCode();
42 | }
43 |
44 | return hash;
45 | }
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Tree/Shared/BSTEnumerator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 |
5 | namespace Advanced.Algorithms.DataStructures
6 | {
7 | // implement IEnumerator.
8 | internal class BSTEnumerator : IEnumerator where T : IComparable
9 | {
10 | private readonly bool asc;
11 |
12 | private readonly BSTNodeBase root;
13 | private BSTNodeBase current;
14 |
15 | internal BSTEnumerator(BSTNodeBase root, bool asc = true)
16 | {
17 | this.root = root;
18 | this.asc = asc;
19 | }
20 |
21 | public bool MoveNext()
22 | {
23 | if (root == null)
24 | {
25 | return false;
26 | }
27 |
28 | if (current == null)
29 | {
30 | current = asc ? root.FindMin() : root.FindMax();
31 | return true;
32 | }
33 |
34 | var next = asc ? current.NextHigher() : current.NextLower();
35 | if (next != null)
36 | {
37 | current = next;
38 | return true;
39 | }
40 |
41 | return false;
42 | }
43 |
44 | public void Reset()
45 | {
46 | current = root;
47 | }
48 |
49 | public T Current
50 | {
51 | get
52 | {
53 | return current.Value;
54 | }
55 | }
56 |
57 | object IEnumerator.Current => Current;
58 |
59 | public void Dispose()
60 | {
61 | current = null;
62 | }
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/DataStructures/Tree/Shared/BSTNodeBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.DataStructures
4 | {
5 | internal abstract class BSTNodeBase where T : IComparable
6 | {
7 | //Count of nodes under this node including this node.
8 | //Used to fasten kth smallest computation.
9 | internal int Count { get; set; } = 1;
10 |
11 | internal virtual BSTNodeBase Parent { get; set; }
12 |
13 | internal virtual BSTNodeBase Left { get; set; }
14 | internal virtual BSTNodeBase Right { get; set; }
15 |
16 | internal T Value { get; set; }
17 |
18 | internal bool IsLeftChild => Parent.Left == this;
19 | internal bool IsRightChild => Parent.Right == this;
20 |
21 | internal bool IsLeaf => Left == null && Right == null;
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Distributed/LRUCache.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 |
6 | namespace Advanced.Algorithms.Distributed
7 | {
8 | ///
9 | /// A least recently used cache implemetation.
10 | ///
11 | public class LRUCache
12 | {
13 | private readonly int capacity;
14 |
15 | private Dictionary>> lookUp
16 | = new Dictionary>>();
17 |
18 | private readonly DoublyLinkedList> dll = new DoublyLinkedList>();
19 |
20 | public LRUCache(int capacity)
21 | {
22 | if (capacity <= 0)
23 | {
24 | throw new Exception("Capacity must be a positive integer.");
25 | }
26 | this.capacity = capacity;
27 | }
28 |
29 | ///
30 | /// Time complexity: O(1).
31 | ///
32 | public V Get(K key)
33 | {
34 | if (!lookUp.ContainsKey(key))
35 | return default(V);
36 |
37 | var node = lookUp[key];
38 |
39 | //move lately used node to beginning of ddl
40 | dll.Delete(node);
41 | var newNode = dll.InsertFirst(node.Data);
42 | lookUp[key] = newNode;
43 |
44 | return node.Data.Item2;
45 | }
46 |
47 | ///
48 | /// Time complexity: O(1).
49 | ///
50 | public void Put(K key, V value)
51 | {
52 | //evict last node of ddl if capacity overflows
53 | if (lookUp.Count == capacity)
54 | {
55 | var nodeToEvict = dll.Last();
56 | lookUp.Remove(nodeToEvict.Item1);
57 | dll.DeleteLast();
58 | }
59 |
60 | //insert
61 | var newNode = dll.InsertFirst(new Tuple(key, value));
62 | lookUp.Add(key, newNode);
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/PointInsidePolygon.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Geometry
2 | {
3 | ///
4 | /// Check whether a given point is inside given polygon.
5 | ///
6 | public class PointInsidePolygon
7 | {
8 | public static bool IsInside(Polygon polygon, Point point)
9 | {
10 | //a imaginary ray line from point to right infinity
11 | var rayLine = new Line(point, new Point(double.MaxValue, point.Y));
12 |
13 | var intersectionCount = 0;
14 | for (int i = 0; i < polygon.Edges.Count - 1; i++)
15 | {
16 | var edgeLine = polygon.Edges[i];
17 |
18 | if (LineIntersection.Find(rayLine, edgeLine) != null)
19 | {
20 | intersectionCount++;
21 | }
22 | }
23 |
24 | //should have odd intersections if point is inside the polygon
25 | return intersectionCount % 2 != 0;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/PointRotation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Rotates given point by given angle about given center.
7 | ///
8 | public class PointRotation
9 | {
10 | public static Point Rotate(Point center, Point point, int angle)
11 | {
12 | double angleInRadians = angle * (Math.PI / 180);
13 |
14 | double cosTheta = Math.Cos(angleInRadians);
15 | double sinTheta = Math.Sin(angleInRadians);
16 |
17 | var x = cosTheta * (point.X - center.X) -
18 | sinTheta * (point.Y - center.Y) + center.X;
19 |
20 | var y = sinTheta * (point.X - center.X) +
21 | cosTheta * (point.Y - center.Y) + center.Y;
22 |
23 | return new Point(x, y);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/RectangleIntersection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Rectangle intersection finder.
7 | ///
8 | public class RectangleIntersection
9 | {
10 | ///
11 | /// Returns the rectangle formed by the intersection if do intersect.
12 | /// Otherwise default value of Rectangle struct.
13 | ///
14 | public static Rectangle FindIntersection(Rectangle a, Rectangle b)
15 | {
16 | //check for intersection
17 | if (!DoIntersect(a, b))
18 | {
19 | //no intersection
20 | return null;
21 | }
22 |
23 | var leftTopCorner = new Point
24 | (
25 | Math.Max(a.LeftTop.X, b.LeftTop.X),
26 | Math.Min(a.LeftTop.Y, b.LeftTop.Y)
27 | );
28 |
29 |
30 | var rightBottomCorner = new Point
31 | (
32 | Math.Min(a.RightBottom.X, b.RightBottom.X),
33 | Math.Max(a.RightBottom.Y, b.RightBottom.Y)
34 | );
35 |
36 |
37 | return new Rectangle()
38 | {
39 | LeftTop = leftTopCorner,
40 | RightBottom = rightBottomCorner
41 | };
42 | }
43 |
44 | public static bool DoIntersect(Rectangle a, Rectangle b)
45 | {
46 | //check for intersection
47 | if (a.LeftTop.X > b.RightBottom.X // A is right of B
48 | || a.RightBottom.X < b.LeftTop.X // A is left of B
49 | || a.RightBottom.Y > b.LeftTop.Y //A is above B
50 | || a.LeftTop.Y < b.RightBottom.Y)//A is below B
51 | {
52 | //no intersection
53 | return false;
54 | }
55 |
56 | return true;
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shapes/Line.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Line object.
7 | ///
8 | public class Line
9 | {
10 | public Point Left { get; private set; }
11 | public Point Right { get; private set; }
12 |
13 | public bool IsVertical => Left.X == Right.X;
14 | public bool IsHorizontal => Left.Y == Right.Y;
15 |
16 | public double Slope => slope.Value;
17 |
18 | private Line()
19 | {
20 | slope = new Lazy(() => calcSlope());
21 | }
22 |
23 | internal Line(Point start, Point end, double tolerance)
24 | : this()
25 | {
26 | if (start.X < end.X)
27 | {
28 | Left = start;
29 | Right = end;
30 | }
31 | else if (start.X > end.X)
32 | {
33 | Left = end;
34 | Right = start;
35 | }
36 | else
37 | {
38 | //use Y
39 | if (start.Y < end.Y)
40 | {
41 | Left = start;
42 | Right = end;
43 | }
44 | else
45 | {
46 | Left = end;
47 | Right = start;
48 | }
49 | }
50 | }
51 |
52 | public Line(Point start, Point end, int precision = 5)
53 | : this(start, end, Math.Round(Math.Pow(0.1, precision), precision)) { }
54 |
55 | private readonly Lazy slope;
56 | private double calcSlope()
57 | {
58 | Point left = Left, right = Right;
59 |
60 | //vertical line has infinite slope
61 | if (left.Y == right.Y)
62 | {
63 | return double.MaxValue;
64 | }
65 |
66 | return ((right.Y - left.Y) / (right.X - left.X));
67 | }
68 |
69 | public Line Clone()
70 | {
71 | return new Line(Left.Clone(), Right.Clone());
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shapes/Point.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Geometry
2 | {
3 | ///
4 | /// Point object.
5 | ///
6 | public class Point
7 | {
8 | public Point(double x, double y)
9 | {
10 | X = x;
11 | Y = y;
12 | }
13 |
14 | public double X { get; private set; }
15 | public double Y { get; private set; }
16 |
17 | public override string ToString()
18 | {
19 | return X.ToString("F") + " " + Y.ToString("F");
20 | }
21 |
22 | public Point Clone()
23 | {
24 | return new Point(X, Y);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shapes/Polygon.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Polygon object.
7 | ///
8 | public class Polygon
9 | {
10 | ///
11 | /// Create a polygon with given edges lines.
12 | ///
13 | public Polygon(List edges)
14 | {
15 | Edges = edges;
16 | }
17 |
18 | ///
19 | /// Create polygon from the given list of consecutive boundary end points.
20 | /// Last and first points will be connected.
21 | /// If only one edge point is provided then this polygon will behave like a point,
22 | /// a line is created with both ends having same edge point.
23 | ///
24 | public Polygon(List edgePoints)
25 | {
26 | Edges = new List();
27 |
28 | for (int i = 0; i < edgePoints.Count; i++)
29 | {
30 | Edges.Add(new Line(edgePoints[i], edgePoints[(i + 1) % edgePoints.Count]));
31 | }
32 |
33 | }
34 |
35 | public List Edges { get; set; }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shapes/Rectangle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Geometry
5 | {
6 | ///
7 | /// Rectangle object.
8 | ///
9 | public class Rectangle
10 | {
11 | public Point LeftTop { get; set; }
12 | public Point RightBottom { get; set; }
13 |
14 | public Rectangle() { }
15 |
16 | public Rectangle(Point leftTop, Point rightBottom)
17 | {
18 | if (rightBottom.Y > leftTop.Y)
19 | {
20 | throw new Exception("Top corner should have higher Y value than bottom.");
21 | }
22 |
23 | if (leftTop.X > rightBottom.X)
24 | {
25 | throw new Exception("Right corner should have higher X value than left.");
26 | }
27 |
28 | LeftTop = leftTop;
29 | RightBottom = rightBottom;
30 | }
31 |
32 | internal double Area()
33 | {
34 | return Length * Breadth;
35 | }
36 |
37 | internal double Length => Math.Abs(RightBottom.X - LeftTop.X);
38 | internal double Breadth => Math.Abs(LeftTop.Y - RightBottom.Y);
39 |
40 | public Polygon ToPolygon()
41 | {
42 |
43 | var edges = new List();
44 |
45 | //add all four edge lines of this rectangle
46 | edges.Add(new Line(LeftTop, new Point(RightBottom.X, LeftTop.Y)));
47 | edges.Add(new Line(new Point(RightBottom.X, LeftTop.Y), RightBottom));
48 | edges.Add(new Line(RightBottom, new Point(LeftTop.X, RightBottom.Y)));
49 | edges.Add(new Line(new Point(LeftTop.X, RightBottom.Y), LeftTop));
50 |
51 | return new Polygon(edges);
52 | }
53 |
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shared/DoubleExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | internal static class DoubleExtensions
6 | {
7 | internal static bool IsLessThan(this double a, double b, double tolerance)
8 | {
9 | return (a - b) < -tolerance;
10 | }
11 |
12 | internal static bool IsLessThanOrEqual(this double a, double b, double tolerance)
13 | {
14 | var result = a - b;
15 |
16 | return result < -tolerance || Math.Abs(result) < tolerance;
17 | }
18 |
19 | internal static bool IsGreaterThan(this double a, double b, double tolerance)
20 | {
21 | return (a - b) > tolerance;
22 | }
23 |
24 | internal static bool IsGreaterThanOrEqual(this double a, double b, double tolerance)
25 | {
26 | var result = a - b;
27 | return result > tolerance || Math.Abs(result) < tolerance;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shared/PointComparer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Compares two points for geometric equality implementing IEqualityComparer.
7 | ///
8 | public class PointComparer : IEqualityComparer
9 | {
10 | public bool Equals(Point x, Point y)
11 | {
12 | if (x == null && y == null)
13 | {
14 | return true;
15 | }
16 |
17 | // Check for null values
18 | if (x == null || y == null)
19 | {
20 | return false;
21 | }
22 |
23 | if (x == y)
24 | {
25 | return true;
26 | }
27 |
28 | return x.X == y.X && x.Y == y.Y;
29 | }
30 |
31 | public int GetHashCode(Point point)
32 | {
33 | var hashCode = 33;
34 | hashCode = hashCode * -21 + point.X.GetHashCode();
35 | hashCode = hashCode * -21 + point.Y.GetHashCode();
36 | return hashCode;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Geometry/Shared/RectangleComparer.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Advanced.Algorithms.Geometry
4 | {
5 | ///
6 | /// Compares two rectangles for geometrical equality implementing IEqualityComparer.
7 | ///
8 | public class RectangleComparer : IEqualityComparer
9 | {
10 | public bool Equals(Rectangle x, Rectangle y)
11 | {
12 | if (x == null && y == null)
13 | {
14 | return true;
15 | }
16 |
17 | // Check for null values
18 | if (x == null || y == null)
19 | {
20 | return false;
21 | }
22 |
23 | return x.LeftTop.X == y.LeftTop.X
24 | && x.LeftTop.Y == y.LeftTop.Y
25 | && x.RightBottom.X == y.RightBottom.X
26 | && x.RightBottom.Y == y.RightBottom.Y;
27 |
28 | }
29 |
30 | public int GetHashCode(Rectangle rectangle)
31 | {
32 | var hashCode = 35;
33 | hashCode = hashCode * -26 + rectangle.LeftTop.GetHashCode();
34 | hashCode = hashCode * -26 + rectangle.RightBottom.GetHashCode();
35 | return hashCode;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Connectivity/TarjansBiConnected.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 |
3 | namespace Advanced.Algorithms.Graph
4 | {
5 | ///
6 | /// Finds if a graph is BiConnected.
7 | ///
8 | public class TarjansBiConnected
9 | {
10 | ///
11 | /// This is using ariticulation alogrithm based on the observation that
12 | /// a graph is BiConnected if and only if there is no articulation Points.
13 | ///
14 | public bool IsBiConnected(IGraph graph)
15 | {
16 | var algorithm = new TarjansArticulationFinder();
17 | return algorithm.FindArticulationPoints(graph).Count == 0;
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Cover/MinVertexCover.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Graph
5 | {
6 | ///
7 | /// A minimum vertex conver algorithm implementation.
8 | ///
9 | public class MinVertexCover
10 | {
11 | public List> GetMinVertexCover(IGraph graph)
12 | {
13 | return getMinVertexCover(graph.ReferenceVertex, new HashSet>(),
14 | new List>());
15 | }
16 |
17 | ///
18 | /// An approximation algorithm for NP complete vertex cover problem.
19 | /// Add a random edge vertices until done visiting all edges.
20 | ///
21 | private List> getMinVertexCover(IGraphVertex vertex,
22 | HashSet> visited, List> cover)
23 | {
24 | visited.Add(vertex);
25 |
26 | foreach (var edge in vertex.Edges)
27 | {
28 | if (!cover.Contains(vertex) && !cover.Contains(edge.TargetVertex))
29 | {
30 | cover.Add(vertex);
31 | cover.Add(edge.TargetVertex);
32 | }
33 |
34 | if (!visited.Contains(edge.TargetVertex))
35 | {
36 | getMinVertexCover(edge.TargetVertex, visited, cover);
37 | }
38 | }
39 |
40 | return cover;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Cycle/CycleDetection.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Graph
5 | {
6 | ///
7 | /// Cycle detection using Depth First Search.
8 | ///
9 | public class CycleDetector
10 | {
11 | ///
12 | /// Returns true if a cycle exists
13 | ///
14 | public bool HasCycle(IDiGraph graph)
15 | {
16 | var visiting = new HashSet();
17 | var visited = new HashSet();
18 |
19 | foreach (var vertex in graph.VerticesAsEnumberable)
20 | {
21 | if (!visited.Contains(vertex.Key))
22 | {
23 | if (dfs(vertex, visited, visiting))
24 | {
25 | return true;
26 | }
27 | }
28 | }
29 |
30 | return false;
31 | }
32 |
33 | private bool dfs(IDiGraphVertex current,
34 | HashSet visited, HashSet visiting)
35 | {
36 | visiting.Add(current.Key);
37 |
38 | foreach (var edge in current.OutEdges)
39 | {
40 | //if we encountered a visiting vertex again
41 | //then their is a cycle
42 | if (visiting.Contains(edge.TargetVertexKey))
43 | {
44 | return true;
45 | }
46 |
47 | if (visited.Contains(edge.TargetVertexKey))
48 | {
49 | continue;
50 | }
51 |
52 | if (dfs(edge.TargetVertex, visited, visiting))
53 | {
54 | return true;
55 | }
56 |
57 | }
58 |
59 | visiting.Remove(current.Key);
60 | visited.Add(current.Key);
61 |
62 | return false;
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Search/BreadthFirst.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Graph
5 | {
6 | ///
7 | /// Bread First Search implementation.
8 | ///
9 | public class BreadthFirst
10 | {
11 | ///
12 | /// Returns true if item exists.
13 | ///
14 | public bool Find(IGraph graph, T vertex)
15 | {
16 | return bfs(graph.ReferenceVertex, new HashSet(), vertex);
17 | }
18 |
19 | ///
20 | /// BFS implementation.
21 | ///
22 | private bool bfs(IGraphVertex referenceVertex,
23 | HashSet visited, T searchVertex)
24 | {
25 | var bfsQueue = new Queue>();
26 |
27 | bfsQueue.Enqueue(referenceVertex);
28 | visited.Add(referenceVertex.Key);
29 |
30 | while (bfsQueue.Count > 0)
31 | {
32 | var current = bfsQueue.Dequeue();
33 |
34 | if (current.Key.Equals(searchVertex))
35 | {
36 | return true;
37 | }
38 |
39 | foreach (var edge in current.Edges)
40 | {
41 | if (visited.Contains(edge.TargetVertexKey))
42 | {
43 | continue;
44 | }
45 |
46 | visited.Add(edge.TargetVertexKey);
47 | bfsQueue.Enqueue(edge.TargetVertex);
48 | }
49 | }
50 |
51 | return false;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Search/DepthFirst.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Graph
5 | {
6 | ///
7 | /// Depth First Search.
8 | ///
9 | public class DepthFirst
10 | {
11 | ///
12 | /// Returns true if item exists.
13 | ///
14 | public bool Find(IGraph graph, T vertex)
15 | {
16 | return dfs(graph.ReferenceVertex, new HashSet(), vertex);
17 | }
18 |
19 | ///
20 | /// Recursive DFS.
21 | ///
22 | private bool dfs(IGraphVertex current,
23 | HashSet visited, T searchVetex)
24 | {
25 | visited.Add(current.Key);
26 |
27 | if (current.Key.Equals(searchVetex))
28 | {
29 | return true;
30 | }
31 |
32 | foreach (var edge in current.Edges)
33 | {
34 | if (visited.Contains(edge.TargetVertexKey))
35 | {
36 | continue;
37 | }
38 |
39 | if (dfs(edge.TargetVertex, visited, searchVetex))
40 | {
41 | return true;
42 | }
43 | }
44 |
45 | return false;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Graph/Sort/DepthFirstTopSort.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Graph
5 | {
6 | ///
7 | /// Find Toplogical order of a graph using Depth First Search.
8 | ///
9 | public class DepthFirstTopSort
10 | {
11 | ///
12 | /// Returns the vertices in Topologically Sorted Order.
13 | ///
14 | public List GetTopSort(IDiGraph graph)
15 | {
16 | var pathStack = new Stack();
17 | var visited = new HashSet();
18 |
19 | //we need a loop so that we can reach all vertices
20 | foreach (var vertex in graph.VerticesAsEnumberable)
21 | {
22 | if (!visited.Contains(vertex.Key))
23 | {
24 | dfs(vertex, visited, pathStack);
25 | }
26 |
27 | }
28 |
29 | //now just pop the stack to result
30 | var result = new List();
31 | while (pathStack.Count > 0)
32 | {
33 | result.Add(pathStack.Pop());
34 | }
35 |
36 | return result;
37 | }
38 |
39 | ///
40 | /// Do a depth first search.
41 | ///
42 | private void dfs(IDiGraphVertex vertex,
43 | HashSet visited, Stack pathStack)
44 | {
45 | visited.Add(vertex.Key);
46 |
47 | foreach (var edge in vertex.OutEdges)
48 | {
49 | if (!visited.Contains(edge.TargetVertexKey))
50 | {
51 | dfs(edge.TargetVertex, visited, pathStack);
52 | }
53 | }
54 |
55 | //add vertex to stack after all edges are visited
56 | pathStack.Push(vertex.Key);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Numerical/Exponentiation.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Numerical
2 | {
3 | ///
4 | /// A fast exponentiation algorithm implementation.
5 | ///
6 | public class FastExponentiation
7 | {
8 | ///
9 | /// Computes exponentiation using squaring.
10 | ///
11 | public static int BySquaring(int @base, int power)
12 | {
13 | while (true)
14 | {
15 | //using the algebraic result
16 | //a^-n = (1/a)^n
17 | if (power < 0)
18 | {
19 | @base = 1 / @base;
20 | power = -power;
21 | continue;
22 | }
23 |
24 | switch (power)
25 | {
26 | case 0:
27 | return 1;
28 | case 1:
29 | return @base;
30 | default:
31 | if (power % 2 == 0)
32 | {
33 | @base = @base * @base;
34 | power = power / 2;
35 | continue;
36 | }
37 | //power is odd
38 | else
39 | {
40 | return @base * BySquaring(@base * @base, (power - 1) / 2);
41 | }
42 | }
43 | }
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Numerical/PrimeGenerator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Numerical
5 | {
6 | ///
7 | /// A prime number generation algorithm using Sieve of Eratosthenes.
8 | ///
9 | public class PrimeGenerator
10 | {
11 | public static List GetAllPrimes(int max)
12 | {
13 | var primeTable = new bool[max + 1];
14 |
15 | var sqrt = Math.Sqrt(max);
16 |
17 | for (int i = 2; i < sqrt; i++)
18 | {
19 | //mark multiples of current number as true
20 | if (primeTable[i])
21 | {
22 | continue;
23 | }
24 |
25 | for (var j = 2 * i; j <= max; j = j + i)
26 | {
27 | primeTable[j] = true;
28 | }
29 | }
30 |
31 | //now write back results
32 | var result = new List();
33 |
34 | for (var i = 2; i < primeTable.Length; i++)
35 | {
36 | if (!primeTable[i])
37 | {
38 | result.Add(i);
39 | }
40 | }
41 |
42 | return result;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Numerical/PrimeTester.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Advanced.Algorithms.Numerical
4 | {
5 | ///
6 | /// Tests for Prime in School method optimized.
7 | ///
8 | public class PrimeTester
9 | {
10 | ///
11 | /// Check if given number is prime.
12 | ///
13 | public static bool IsPrime(int number)
14 | {
15 | if (number <= 1)
16 | {
17 | return false;
18 | }
19 |
20 | if (number <= 3)
21 | {
22 | return true;
23 | }
24 |
25 | //number can be divided by 2 or 3
26 | if (number % 2 == 0 || number % 3 == 0)
27 | {
28 | return false;
29 | }
30 |
31 | //skip six numbers in each step
32 | //since we don't need to check for 3 even numbers
33 | //and one number divisible by 3
34 | //inside the loop
35 | //check until square root of number
36 | var sqrt = Math.Sqrt(number);
37 | for (var i = 5; i <= sqrt; i = i + 6)
38 | {
39 | //check for two potential primes
40 | if (number % i == 0 || number % (i + 2) == 0)
41 | {
42 | return false;
43 | }
44 | }
45 |
46 | return true;
47 | }
48 |
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Search/BinarySearch.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms.Search
2 | {
3 | ///
4 | /// A binary search algorithm implementation.
5 | ///
6 | public class BinarySearch
7 | {
8 | public static int Search(int[] input, int element)
9 | {
10 | return search(input, 0, input.Length - 1, element);
11 | }
12 |
13 | private static int search(int[] input, int i, int j, int element)
14 | {
15 | while (true)
16 | {
17 | if (i == j)
18 | {
19 | if (input[i] == element)
20 | {
21 | return i;
22 | }
23 |
24 | return -1;
25 | }
26 |
27 | var mid = (i + j) / 2;
28 |
29 | if (input[mid] == element)
30 | {
31 | return mid;
32 | }
33 |
34 | if (input[mid] > element)
35 | {
36 | j = mid;
37 | continue;
38 | }
39 |
40 | i = mid + 1;
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Search/BoyerMoore.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Search
6 | {
7 | ///
8 | /// A boyer-moore majority finder algorithm implementation.
9 | ///
10 | public class BoyerMoore where T : IComparable
11 | {
12 | public static T FindMajority(IEnumerable input)
13 | {
14 | var candidate = findMajorityCandidate(input, input.Count());
15 |
16 | if (verify(input, input.Count(), candidate))
17 | {
18 | return candidate;
19 | }
20 |
21 | return default(T);
22 | }
23 |
24 | //Find majority candidate
25 | private static T findMajorityCandidate(IEnumerable input, int length)
26 | {
27 | int count = 1;
28 | T candidate = input.First();
29 |
30 | foreach (var element in input.Skip(1))
31 | {
32 | if (candidate.Equals(element))
33 | {
34 | count++;
35 | }
36 | else
37 | {
38 | count--;
39 | }
40 |
41 | if (count == 0)
42 | {
43 | candidate = element;
44 | count = 1;
45 | }
46 | }
47 |
48 | return candidate;
49 | }
50 |
51 | //verify that candidate is indeed the majority
52 | private static bool verify(IEnumerable input, int size, T candidate)
53 | {
54 | return input.Count(x => x.Equals(candidate)) > size / 2;
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Shared/CustomComparer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms
5 | {
6 | internal class CustomComparer : IComparer where T : IComparable
7 | {
8 | private readonly bool isMax;
9 | private readonly IComparer comparer;
10 |
11 | internal CustomComparer(SortDirection sortDirection, IComparer comparer)
12 | {
13 | this.isMax = sortDirection == SortDirection.Descending;
14 | this.comparer = comparer;
15 | }
16 |
17 | public int Compare(T x, T y)
18 | {
19 | return !isMax ? compare(x, y) : compare(y, x);
20 | }
21 |
22 | private int compare(T x, T y)
23 | {
24 | return comparer.Compare(x, y);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Shared/SortDirection.cs:
--------------------------------------------------------------------------------
1 | namespace Advanced.Algorithms
2 | {
3 | public enum SortDirection
4 | {
5 | Ascending = 0,
6 | Descending = 1
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/BubbleSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// A bubble sort implementation.
8 | ///
9 | public class BubbleSort where T : IComparable
10 | {
11 | ///
12 | /// Time complexity: O(n^2).
13 | ///
14 | public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
15 | {
16 | var comparer = new CustomComparer(sortDirection, Comparer.Default);
17 | var swapped = true;
18 |
19 | while (swapped)
20 | {
21 | swapped = false;
22 |
23 | for (int i = 0; i < array.Length - 1; i++)
24 | {
25 | //compare adjacent elements
26 | if (comparer.Compare(array[i], array[i + 1]) > 0)
27 | {
28 | var temp = array[i];
29 | array[i] = array[i + 1];
30 | array[i + 1] = temp;
31 | swapped = true;
32 | }
33 | }
34 | }
35 |
36 | return array;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/BucketSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Sorting
6 | {
7 |
8 | ///
9 | /// A bucket sort implementation.
10 | ///
11 | public class BucketSort
12 | {
13 | ///
14 | /// Sort given integers using bucket sort with merge sort as sub sort.
15 | ///
16 | public static int[] Sort(int[] array, int bucketSize, SortDirection sortDirection = SortDirection.Ascending)
17 | {
18 | if (bucketSize < 0 || bucketSize > array.Length)
19 | {
20 | throw new Exception("Invalid bucket size.");
21 | }
22 |
23 | var buckets = new Dictionary>();
24 |
25 | int i;
26 | for (i = 0; i < array.Length; i++)
27 | {
28 | if (bucketSize == 0)
29 | {
30 | continue;
31 | }
32 |
33 | var bucketIndex = array[i] / bucketSize;
34 |
35 | if (!buckets.ContainsKey(bucketIndex))
36 | {
37 | buckets.Add(bucketIndex, new List());
38 | }
39 |
40 | buckets[bucketIndex].Add(array[i]);
41 | }
42 |
43 | i = 0;
44 | var bucketKeys = new int[buckets.Count];
45 | foreach (var bucket in buckets.ToList())
46 | {
47 | buckets[bucket.Key] = new List(MergeSort
48 | .Sort(bucket.Value.ToArray(), sortDirection));
49 |
50 | bucketKeys[i] = bucket.Key;
51 | i++;
52 | }
53 |
54 | bucketKeys = MergeSort.Sort(bucketKeys, sortDirection);
55 |
56 | var result = new int[array.Length];
57 |
58 | i = 0;
59 | foreach (var bucketKey in bucketKeys)
60 | {
61 | var bucket = buckets[bucketKey];
62 | Array.Copy(bucket.ToArray(), 0, result, i, bucket.Count);
63 | i += bucket.Count;
64 | }
65 |
66 | return result;
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/HeapSort.cs:
--------------------------------------------------------------------------------
1 |
2 | /* Unmerged change from project 'Advanced.Algorithms (netstandard1.0)'
3 | Before:
4 | using System;
5 | After:
6 | using Advanced.Algorithms.DataStructures;
7 | using System;
8 | */
9 | using Advanced.Algorithms.DataStructures;
10 |
11 | /* Unmerged change from project 'Advanced.Algorithms (netstandard1.0)'
12 | Before:
13 | using System.Linq;
14 | using Advanced.Algorithms.DataStructures;
15 | After:
16 | using System.Linq;
17 | */
18 | using System;
19 | using System.Collections.Generic;
20 |
21 | namespace Advanced.Algorithms.Sorting
22 | {
23 | ///
24 | /// A heap sort implementation.
25 | ///
26 | public class HeapSort where T : IComparable
27 | {
28 | ///
29 | /// Time complexity: O(nlog(n)).
30 | ///
31 | public static T[] Sort(ICollection collection, SortDirection sortDirection = SortDirection.Ascending)
32 | {
33 | //heapify
34 | var heap = new BHeap(sortDirection, collection);
35 |
36 | //now extract min until empty and return them as sorted array
37 | var sortedArray = new T[collection.Count];
38 | var j = 0;
39 | while (heap.Count > 0)
40 | {
41 | sortedArray[j] = heap.Extract();
42 | j++;
43 | }
44 |
45 | return sortedArray;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/InsertionSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// An insertion sort implementation.
8 | ///
9 | public class InsertionSort where T : IComparable
10 | {
11 | ///
12 | /// Time complexity: O(n^2).
13 | ///
14 | public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
15 | {
16 | var comparer = new CustomComparer(sortDirection, Comparer.Default);
17 |
18 | for (int i = 0; i < array.Length - 1; i++)
19 | {
20 | for (int j = i + 1; j > 0; j--)
21 | {
22 | if (comparer.Compare(array[j], array[j - 1]) < 0)
23 | {
24 | var temp = array[j - 1];
25 | array[j - 1] = array[j];
26 | array[j] = temp;
27 | }
28 | else
29 | {
30 | break;
31 | }
32 | }
33 | }
34 |
35 | return array;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/QuickSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// A quick sort implementation.
8 | ///
9 | public class QuickSort where T : IComparable
10 | {
11 | ///
12 | /// Time complexity: O(n^2)
13 | ///
14 | public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
15 | {
16 | if (array.Length <= 1)
17 | {
18 | return array;
19 | }
20 |
21 | var comparer = new CustomComparer(sortDirection, Comparer.Default);
22 |
23 | sort(array, 0, array.Length - 1, comparer);
24 |
25 | return array;
26 | }
27 |
28 | private static void sort(T[] array, int startIndex, int endIndex, CustomComparer comparer)
29 | {
30 | while (true)
31 | {
32 | //if only one element the do nothing
33 | if (startIndex < 0 || endIndex < 0 || endIndex - startIndex < 1)
34 | {
35 | return;
36 | }
37 |
38 | //set the wall to the left most index
39 | var wall = startIndex;
40 |
41 | //pick last index element on array as comparison pivot
42 | var pivot = array[endIndex];
43 |
44 | //swap elements greater than pivot to the right side of wall
45 | //others will be on left
46 | for (var j = wall; j <= endIndex; j++)
47 | {
48 | if (comparer.Compare(pivot, array[j]) <= 0 && j != endIndex)
49 | {
50 | continue;
51 | }
52 |
53 | var temp = array[wall];
54 | array[wall] = array[j];
55 | array[j] = temp;
56 | //increment to exclude the minimum element in subsequent comparisons
57 | wall++;
58 | }
59 |
60 | //sort left
61 | sort(array, startIndex, wall - 2, comparer);
62 | //sort right
63 | startIndex = wall;
64 | }
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/RadixSort.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// A radix sort implementation.
8 | ///
9 | public class RadixSort
10 | {
11 | public static int[] Sort(int[] array, SortDirection sortDirection = SortDirection.Ascending)
12 | {
13 | int i;
14 | for (i = 0; i < array.Length; i++)
15 | {
16 | if (array[i] < 0)
17 | {
18 | throw new System.Exception("Negative numbers not supported.");
19 | }
20 | }
21 |
22 | var @base = 1;
23 | var max = array.Max();
24 |
25 |
26 | while (max / @base > 0)
27 | {
28 | //create a bucket for digits 0 to 9
29 | var buckets = new List[10];
30 |
31 | for (i = 0; i < array.Length; i++)
32 | {
33 | var bucketIndex = array[i] / @base % 10;
34 |
35 | if (buckets[bucketIndex] == null)
36 | {
37 | buckets[bucketIndex] = new List();
38 | }
39 |
40 | buckets[bucketIndex].Add(array[i]);
41 | }
42 |
43 | //now update array with what is in buckets
44 | var orderedBuckets = sortDirection == SortDirection.Ascending ?
45 | buckets : buckets.Reverse();
46 |
47 | i = 0;
48 | foreach (var bucket in orderedBuckets.Where(x => x != null))
49 | {
50 | foreach (var item in bucket)
51 | {
52 | array[i] = item;
53 | i++;
54 | }
55 | }
56 |
57 | @base *= 10;
58 | }
59 |
60 | return array;
61 | }
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/SelectionSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// A selection sort implementation.
8 | ///
9 | public class SelectionSort where T : IComparable
10 | {
11 | ///
12 | /// Time complexity: O(n^2).
13 | ///
14 | public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
15 | {
16 | var comparer = new CustomComparer(sortDirection, Comparer.Default);
17 |
18 | for (int i = 0; i < array.Length; i++)
19 | {
20 | //select the smallest item in sub array and move it to front
21 | for (int j = i + 1; j < array.Length; j++)
22 | {
23 | if (comparer.Compare(array[j], array[i]) >= 0)
24 | {
25 | continue;
26 | }
27 |
28 | var temp = array[i];
29 | array[i] = array[j];
30 | array[j] = temp;
31 | }
32 | }
33 |
34 | return array;
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/ShellSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Advanced.Algorithms.Sorting
5 | {
6 | ///
7 | /// A shell sort implementation.
8 | ///
9 | public class ShellSort where T : IComparable
10 | {
11 | public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
12 | {
13 | var comparer = new CustomComparer(sortDirection, Comparer.Default);
14 |
15 | var k = array.Length / 2;
16 | var j = 0;
17 |
18 | while (k >= 1)
19 | {
20 | for (int i = k; i < array.Length; i = i + k, j = j + k)
21 | {
22 | if (comparer.Compare(array[i], array[j]) >= 0)
23 | {
24 | continue;
25 | }
26 |
27 | swap(array, i, j);
28 |
29 | if (i <= k)
30 | {
31 | continue;
32 | }
33 |
34 | i -= k * 2;
35 | j -= k * 2;
36 | }
37 |
38 | j = 0;
39 | k /= 2;
40 | }
41 |
42 | return array;
43 | }
44 |
45 | private static void swap(T[] array, int i, int j)
46 | {
47 | var tmp = array[i];
48 | array[i] = array[j];
49 | array[j] = tmp;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/Sorting/TreeSort.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 |
6 | namespace Advanced.Algorithms.Sorting
7 | {
8 | ///
9 | /// A tree sort implementation.
10 | ///
11 | public class TreeSort where T : IComparable
12 | {
13 | ///
14 | /// Time complexity: O(nlog(n)).
15 | ///
16 | public static IEnumerable Sort(IEnumerable enumerable, SortDirection sortDirection = SortDirection.Ascending)
17 | {
18 | //create BST
19 | var tree = new RedBlackTree();
20 | foreach (var item in enumerable)
21 | {
22 | tree.Insert(item);
23 | }
24 |
25 | return sortDirection == SortDirection.Ascending ?
26 | tree.AsEnumerable() : tree.AsEnumerableDesc();
27 |
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/StrongNameKey.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unitycoder/Advanced-Algorithms/6ce425ed0fa63afef9d9fb97e0cbdae7a06a0d33/src/Advanced.Algorithms/StrongNameKey.snk
--------------------------------------------------------------------------------
/src/Advanced.Algorithms/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Advanced.Algorithms.Tests.Mono.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Advanced.Algorithms.Tests
5 | net45
6 | false
7 | false
8 | True
9 | StrongNameKey.snk
10 | Advanced.Algorithms.Tests
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Advanced.Algorithms.Tests.NetCore.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Advanced.Algorithms.Tests
5 | netcoreapp2.0
6 | false
7 | false
8 | True
9 | StrongNameKey.snk
10 | False
11 | Advanced.Algorithms.Tests
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Binary/BaseConversion_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Binary;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 | namespace Advanced.Algorithms.Tests.Binary
5 | {
6 | [TestClass]
7 | public class BaseConversion_Tests
8 | {
9 | [TestMethod]
10 | public void BaseConversion_Smoke_Test()
11 | {
12 | //decimal to binary
13 | Assert.AreEqual("11",
14 | BaseConversion.Convert("1011", "01",
15 | "0123456789"));
16 |
17 | //binary to decimal
18 | Assert.AreEqual("11.5",
19 | BaseConversion.Convert("1011.10", "01",
20 | "0123456789"));
21 |
22 | //decimal to base3
23 | Assert.AreEqual("Foo",
24 | BaseConversion.Convert("9", "0123456789",
25 | "oF8"));
26 |
27 | //base3 to decimal
28 | Assert.AreEqual("9",
29 | BaseConversion.Convert("Foo", "oF8",
30 | "0123456789"));
31 |
32 | //hex to binary
33 | Assert.AreEqual("10011",
34 | BaseConversion.Convert("13", "0123456789abcdef",
35 | "01"));
36 |
37 | //decimal to hex
38 | Assert.AreEqual("5.0e631f8a0902de00d1b71758e219652b",
39 | BaseConversion.Convert("5.05620", "0123456789",
40 | "0123456789abcdef"));
41 |
42 | //hex to decimal with precision 5
43 | Assert.AreEqual("5.05619",
44 | BaseConversion.Convert("5.0e631f8a0902de00d1b71758e219652b", "0123456789abcdef",
45 | "0123456789", 5));
46 |
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Binary/GCD_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Binary;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 | namespace Advanced.Algorithms.Tests.Binary
5 | {
6 | [TestClass]
7 | public class GCD_Tests
8 | {
9 | [TestMethod]
10 | public void GCD_Smoke_Test()
11 | {
12 | Assert.AreEqual(3, Gcd.Find(-9, 3));
13 | Assert.AreEqual(15, Gcd.Find(45, 30));
14 |
15 | Assert.AreEqual(1, Gcd.Find(3, 5));
16 |
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Binary/Logarithm_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Binary;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 |
5 | namespace Advanced.Algorithms.Tests.Binary
6 | {
7 | [TestClass]
8 | public class Logarithm_Tests
9 | {
10 | [TestMethod]
11 | public void Logarithm_Smoke_Test()
12 | {
13 | Assert.AreEqual(3, Logarithm.CalcBase2LogFloor(9));
14 | Assert.AreEqual(3, Logarithm.CalcBase2LogFloor(8));
15 | Assert.AreEqual(5, Logarithm.CalcBase2LogFloor(32));
16 |
17 | Assert.AreEqual(2, Logarithm.CalcBase10LogFloor(102));
18 | Assert.AreEqual(3, Logarithm.CalcBase10LogFloor(1000));
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Combinatorics/Combination_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Combinatorics;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System;
4 | using System.Linq;
5 |
6 | namespace Advanced.Algorithms.Tests.Combinatorics
7 | {
8 | [TestClass]
9 | public class Combination_Tests
10 | {
11 | //for verification
12 | static readonly Func factorial = n => n == 0 ? 1 :
13 | Enumerable.Range(1, n).Aggregate((acc, x) => acc * x);
14 |
15 | //for verification
16 | static readonly Func combination = (int n, int r)
17 | => n == 0 || r == 0 ? 0 : factorial(n) / (factorial(r) * factorial(n - r));
18 |
19 | [TestMethod]
20 | public void Combination_Without_Repetitions_Smoke_Test()
21 | {
22 | var input = "".ToCharArray().ToList();
23 | var combinations = Combination.Find(input, 2, false);
24 | Assert.AreEqual(combination(input.Count, 2), combinations.Count);
25 |
26 | input = "cookie".ToCharArray().ToList();
27 | combinations = Combination.Find(input, 3, false);
28 | Assert.AreEqual(combination(input.Count, 3), combinations.Count);
29 |
30 | input = "monster".ToCharArray().ToList();
31 | combinations = Combination.Find(input, 4, false);
32 | Assert.AreEqual(combination(input.Count, 4), combinations.Count);
33 | }
34 |
35 |
36 | [TestMethod]
37 | public void Combination_With_Repetitions_Smoke_Test()
38 | {
39 | var input = "".ToCharArray().ToList();
40 | var combinations = Combination.Find(input, 3, true);
41 | Assert.AreEqual(0, combinations.Count);
42 |
43 | input = "pen".ToCharArray().ToList();
44 | combinations = Combination.Find(input, 2, true);
45 | Assert.AreEqual(combination(input.Count + 2 - 1, 2), combinations.Count);
46 |
47 | input = "scan".ToCharArray().ToList();
48 | combinations = Combination.Find(input, 3, true);
49 | Assert.AreEqual(combination(input.Count + 3 - 1, 3), combinations.Count);
50 | }
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Combinatorics/Subset_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Combinatorics;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System;
4 | using System.Linq;
5 |
6 | namespace Advanced.Algorithms.Tests.Combinatorics
7 | {
8 | [TestClass]
9 | public class Subset_Tests
10 | {
11 |
12 | [TestMethod]
13 | public void Subset_Smoke_Test()
14 | {
15 | var input = "".ToCharArray().ToList();
16 | var subsets = Subset.Find(input);
17 | Assert.AreEqual(Math.Pow(2, input.Count), subsets.Count);
18 |
19 | input = "cookie".ToCharArray().ToList();
20 | subsets = Subset.Find(input);
21 | Assert.AreEqual(Math.Pow(2, input.Count), subsets.Count);
22 |
23 | input = "monster".ToCharArray().ToList();
24 | subsets = Subset.Find(input);
25 | Assert.AreEqual(Math.Pow(2, input.Count), subsets.Count);
26 | }
27 |
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/Compression/HuffmanCoding_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.Compression;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 | namespace Advanced.Algorithms.Tests.Compression
5 | {
6 | [TestClass]
7 | public class HuffmanCoding_Tests
8 | {
9 | [TestMethod]
10 | public void HuffmanCoding_Test()
11 | {
12 | var encoder = new HuffmanCoding();
13 |
14 | var compressed = encoder
15 | .Compress("abcasdasdasdcaaaaaadqwerdasd".ToCharArray());
16 |
17 | Assert.AreEqual(compressed['a'].Length, 1);
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/DataStructures/Graph/AdjacencyList/DiGraph_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph.AdjacencyList;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Tests.DataStructures.Graph.AdjacencyList
6 | {
7 | [TestClass]
8 | public class DiGraph_Tests
9 | {
10 | ///
11 | /// key value dictionary tests
12 | ///
13 | [TestMethod]
14 | public void DiGraph_Smoke_Test()
15 | {
16 | var graph = new DiGraph();
17 |
18 | graph.AddVertex(1);
19 | graph.AddVertex(2);
20 | graph.AddVertex(3);
21 | graph.AddVertex(4);
22 | graph.AddVertex(5);
23 |
24 | graph.AddEdge(1, 2);
25 | Assert.IsTrue(graph.HasEdge(1, 2));
26 | Assert.IsFalse(graph.HasEdge(2, 1));
27 |
28 | graph.AddEdge(2, 3);
29 | graph.AddEdge(3, 4);
30 | graph.AddEdge(4, 5);
31 | graph.AddEdge(4, 1);
32 | graph.AddEdge(3, 5);
33 |
34 | //IEnumerable test using linq
35 | Assert.AreEqual(graph.VerticesCount, graph.Count());
36 |
37 | Assert.AreEqual(2, graph.OutEdges(4).Count());
38 | Assert.AreEqual(2, graph.InEdges(5).Count());
39 |
40 | Assert.AreEqual(5, graph.VerticesCount);
41 |
42 | Assert.IsTrue(graph.HasEdge(1, 2));
43 |
44 | graph.RemoveEdge(1, 2);
45 |
46 | Assert.IsFalse(graph.HasEdge(1, 2));
47 |
48 | graph.RemoveEdge(2, 3);
49 | graph.RemoveEdge(3, 4);
50 | graph.RemoveEdge(4, 5);
51 | graph.RemoveEdge(4, 1);
52 |
53 | Assert.IsTrue(graph.HasEdge(3, 5));
54 | graph.RemoveEdge(3, 5);
55 | Assert.IsFalse(graph.HasEdge(3, 5));
56 |
57 | graph.RemoveVertex(1);
58 | graph.RemoveVertex(2);
59 | graph.RemoveVertex(3);
60 | graph.RemoveVertex(4);
61 |
62 | graph.AddEdge(5, 5);
63 | graph.RemoveEdge(5, 5);
64 | graph.RemoveVertex(5);
65 |
66 | Assert.AreEqual(0, graph.VerticesCount);
67 |
68 | //IEnumerable test using linq
69 | Assert.AreEqual(graph.VerticesCount, graph.Count());
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/DataStructures/Graph/AdjacencyList/Graph_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph.AdjacencyList;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Tests.DataStructures.Graph.AdjacencyList
6 | {
7 | [TestClass]
8 | public class Graph_Tests
9 | {
10 | ///
11 | /// key value dictionary tests
12 | ///
13 | [TestMethod]
14 | public void Graph_Smoke_Test()
15 | {
16 | var graph = new Graph();
17 |
18 | graph.AddVertex(1);
19 | graph.AddVertex(2);
20 | graph.AddVertex(3);
21 | graph.AddVertex(4);
22 | graph.AddVertex(5);
23 |
24 | graph.AddEdge(1, 2);
25 | graph.AddEdge(2, 3);
26 | graph.AddEdge(3, 4);
27 | graph.AddEdge(4, 5);
28 | graph.AddEdge(4, 1);
29 | graph.AddEdge(3, 5);
30 |
31 | Assert.AreEqual(3, graph.Edges(4).Count());
32 |
33 | Assert.AreEqual(5, graph.VerticesCount);
34 |
35 | Assert.IsTrue(graph.HasEdge(1, 2));
36 |
37 | graph.RemoveEdge(1, 2);
38 |
39 | Assert.IsFalse(graph.HasEdge(1, 2));
40 |
41 | graph.RemoveEdge(2, 3);
42 | graph.RemoveEdge(3, 4);
43 | graph.RemoveEdge(4, 5);
44 | graph.RemoveEdge(4, 1);
45 |
46 |
47 | Assert.IsTrue(graph.HasEdge(3, 5));
48 | graph.RemoveEdge(3, 5);
49 | Assert.IsFalse(graph.HasEdge(3, 5));
50 |
51 | graph.RemoveVertex(1);
52 | graph.RemoveVertex(2);
53 | graph.RemoveVertex(3);
54 | graph.RemoveVertex(4);
55 |
56 | graph.AddEdge(5, 5);
57 | graph.RemoveEdge(5, 5);
58 | graph.RemoveVertex(5);
59 |
60 | Assert.AreEqual(0, graph.VerticesCount);
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/DataStructures/Graph/AdjacencyList/WeightedDiGraph_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph.AdjacencyList;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Tests.DataStructures.Graph.AdjacencyList
6 | {
7 | [TestClass]
8 | public class WeightedDiGraph_Tests
9 | {
10 | ///
11 | /// key value dictionary tests
12 | ///
13 | [TestMethod]
14 | public void WeightedDiGraph_Smoke_Test()
15 | {
16 | var graph = new WeightedDiGraph();
17 |
18 | graph.AddVertex(1);
19 | graph.AddVertex(2);
20 | graph.AddVertex(3);
21 | graph.AddVertex(4);
22 | graph.AddVertex(5);
23 |
24 | graph.AddEdge(1, 2, 1);
25 | graph.AddEdge(2, 3, 2);
26 | graph.AddEdge(3, 4, 3);
27 | graph.AddEdge(4, 5, 1);
28 | graph.AddEdge(4, 1, 6);
29 | graph.AddEdge(3, 5, 4);
30 |
31 | Assert.AreEqual(2, graph.OutEdges(4).Count());
32 | Assert.AreEqual(2, graph.InEdges(5).Count());
33 |
34 | Assert.AreEqual(5, graph.VerticesCount);
35 |
36 | Assert.IsTrue(graph.HasEdge(1, 2));
37 |
38 | graph.RemoveEdge(1, 2);
39 |
40 | Assert.IsFalse(graph.HasEdge(1, 2));
41 |
42 | graph.RemoveEdge(2, 3);
43 | graph.RemoveEdge(3, 4);
44 | graph.RemoveEdge(4, 5);
45 | graph.RemoveEdge(4, 1);
46 |
47 | Assert.IsTrue(graph.HasEdge(3, 5));
48 | graph.RemoveEdge(3, 5);
49 | Assert.IsFalse(graph.HasEdge(3, 5));
50 |
51 | graph.RemoveVertex(1);
52 | graph.RemoveVertex(2);
53 | graph.RemoveVertex(3);
54 | graph.RemoveVertex(4);
55 | graph.RemoveVertex(5);
56 |
57 | Assert.AreEqual(0, graph.VerticesCount);
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/DataStructures/Graph/AdjacencyList/WeightedGraph_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph.AdjacencyList;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 |
4 | namespace Advanced.Algorithms.Tests.DataStructures.Graph.AdjacencyList
5 | {
6 | [TestClass]
7 | public class WeightedGraph_Tests
8 | {
9 | ///
10 | /// key value dictionary tests
11 | ///
12 | [TestMethod]
13 | public void WeightedGraph_Smoke_Test()
14 | {
15 | var graph = new WeightedGraph();
16 |
17 | graph.AddVertex(1);
18 | graph.AddVertex(2);
19 | graph.AddVertex(3);
20 | graph.AddVertex(4);
21 | graph.AddVertex(5);
22 |
23 | graph.AddEdge(1, 2, 1);
24 | graph.AddEdge(2, 3, 2);
25 | graph.AddEdge(3, 4, 4);
26 | graph.AddEdge(4, 5, 5);
27 | graph.AddEdge(4, 1, 1);
28 | graph.AddEdge(3, 5, 0);
29 |
30 | Assert.AreEqual(3, graph.GetAllEdges(4).Count);
31 | Assert.AreEqual(2, graph.GetAllEdges(5).Count);
32 |
33 | Assert.AreEqual(5, graph.VerticesCount);
34 |
35 | Assert.IsTrue(graph.HasEdge(1, 2));
36 |
37 | graph.RemoveEdge(1, 2);
38 |
39 | Assert.IsFalse(graph.HasEdge(1, 2));
40 |
41 | graph.RemoveEdge(2, 3);
42 | graph.RemoveEdge(3, 4);
43 | graph.RemoveEdge(4, 5);
44 | graph.RemoveEdge(4, 1);
45 |
46 | Assert.IsTrue(graph.HasEdge(3, 5));
47 | graph.RemoveEdge(3, 5);
48 | Assert.IsFalse(graph.HasEdge(3, 5));
49 |
50 | graph.RemoveVertex(1);
51 | graph.RemoveVertex(2);
52 | graph.RemoveVertex(3);
53 | graph.RemoveVertex(4);
54 | graph.RemoveVertex(5);
55 |
56 | Assert.AreEqual(0, graph.VerticesCount);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/tests/Advanced.Algorithms.Tests/DataStructures/Graph/AdjacencyMatrix/DiGraph_Tests.cs:
--------------------------------------------------------------------------------
1 | using Advanced.Algorithms.DataStructures.Graph.AdjacencyMatrix;
2 | using Microsoft.VisualStudio.TestTools.UnitTesting;
3 | using System.Linq;
4 |
5 | namespace Advanced.Algorithms.Tests.DataStructures.Graph.AdjacencyMatrix
6 | {
7 | [TestClass]
8 | public class DiGraph_Tests
9 | {
10 | ///