public static void DoTest() { MinBinaryHeap <long> minHeap = new MinBinaryHeap <long> (Comparer <long> .Default); minHeap.Add(23); minHeap.Add(42); minHeap.Add(4); minHeap.Add(16); minHeap.Add(8); minHeap.Add(15); minHeap.Add(9); minHeap.Add(55); minHeap.Add(0); minHeap.Add(34); minHeap.Add(12); minHeap.Add(2); minHeap.Add(93); minHeap.Add(14); minHeap.Add(27); var array = minHeap.ToArray(); Debug.Assert(array.Length == minHeap.Count(), "Wrong size."); var list = minHeap.ToList(); Debug.Assert(list.Count == minHeap.Count(), "Wrong size."); array.HeapSortDescending(); var maxHeap = minHeap.ToMaxHeap(); Debug.Assert(maxHeap.Peek() == array[0], "Wrong maximum."); }
public void DefaultIsReturnedAsMinimalNodeIfHeapIsEmpty() { var binaryHeap = new MinBinaryHeap <int>(); var minNode = binaryHeap.GetMinKeyOrDefault(); Assert.AreEqual(minNode, default(int)); }
public void TopElementIsInsertedWhenHeapIsEmpty() { var sut = new MinBinaryHeap <int>(); sut.Insert(10); Assert.Equal(10, sut.GetTop()); }
/// <summary>Copies the elements stored in the queue to a new array.</summary> /// <returns>A new array containing a snapshot of elements copied from the queue.</returns> public KeyValuePair <TKey, TValue>[] ToArray() { lock (_syncLock) { if (_useMinHeap) { var clonedHeap = new MinBinaryHeap(_minHeap); var result = new KeyValuePair <TKey, TValue> [_minHeap.Count]; for (int i = 0; i < result.Length; i++) { result[i] = clonedHeap.Remove(); } return(result); } else { var clonedHeap = new MaxBinaryHeap(_maxHeap); var result = new KeyValuePair <TKey, TValue> [_maxHeap.Count]; for (int i = 0; i < result.Length; i++) { result[i] = clonedHeap.Remove(); } return(result); } } }
public void TestLimits() { var heap = new MinBinaryHeap <StreamItemCollection, StreamItem, long>(128); for (int i = 1024; i > 0; i--) { heap.Enqueue(new StreamItemCollection(new[] { new StreamItem() { StreamItemId = i }, })); } var min = long.MinValue; while (heap.Count != 0) { var item = heap.Dequeue(); Assert.True(min < item.StreamItems.First().StreamItemId); min = item.StreamItems.First().StreamItemId; } Assert.True(heap.Count == 0); }
public static Graph <T> CreateMinimumSpanningTreeFor <T>(Graph <T> graph) where T : class, IEquatable <T> { var visitedVertices = new HashSet <Vertex <T> >(); if (!graph.IsConnected || graph.IsDirected) { throw new InvalidOperationException("The graph doesn't meet the characteristics to be used with Prim algorythm."); } var minBinaryHeap = new MinBinaryHeap <T>(graph, graph.Vertices.Values.First()); while (!minBinaryHeap.IsEmpty()) { var vertexOnAnalysis = minBinaryHeap.ExtractFromTop(); foreach (var edge in vertexOnAnalysis.AdjacentEdges.Where(x => !visitedVertices.Contains(x.To) && !visitedVertices.Contains(x.From))) { var other = edge.To == vertexOnAnalysis ? edge.From : edge.To; if (minBinaryHeap.Contains(other, out float?value)) { if (value.Value > edge.Weight.Value) { minBinaryHeap.ReplaceValue(other, edge.Weight.Value, edge); } } } visitedVertices.Add(vertexOnAnalysis); } return(BuildNewGraph(graph, minBinaryHeap)); }
private static Graph <T> BuildNewGraph <T>(Graph <T> graph, MinBinaryHeap <T> minBinaryHeap) where T : class, IEquatable <T> { var newGraph = new Graph <T>(graph.IsWeighted, graph.IsDirected); foreach (var vertex in graph.Vertices.Values.Select(x => x with { AdjacentEdges = null }))
public static void DoTest () { MinBinaryHeap<long> minHeap = new MinBinaryHeap<long> (Comparer<long>.Default); minHeap.Add (23); minHeap.Add (42); minHeap.Add (4); minHeap.Add (16); minHeap.Add (8); minHeap.Add (15); minHeap.Add (9); minHeap.Add (55); minHeap.Add (0); minHeap.Add (34); minHeap.Add (12); minHeap.Add (2); minHeap.Add (93); minHeap.Add (14); minHeap.Add (27); var array = minHeap.ToArray (); Debug.Assert (array.Length == minHeap.Count(), "Wrong size."); var list = minHeap.ToList (); Debug.Assert (list.Count == minHeap.Count(), "Wrong size."); array.HeapSortDescending(); var maxHeap = minHeap.ToMaxHeap (); Debug.Assert (maxHeap.Peek() == array[0], "Wrong maximum."); }
static MinBinaryHeap <int, int> CreateMinBinaryHeap() { MinBinaryHeap <int, int> heap = new MinBinaryHeap <int, int>(); var heapData = GetMinHeapTestData(); heapData.ForEach(x => heap.Insert(x.Key, x.Value)); return(heap); }
public void CreateFromArrayTest() { _minHeap = new MinBinaryHeap <int>(_intArray); int[] heapCopy = new int[_minHeap.Count]; _minHeap.CopyTo(heapCopy, 0); CollectionAssert.AreEquivalent(_intArray, heapCopy); Assert.AreEqual(_intArray.Length, _minHeap.Count); }
/// <summary>Copies the elements stored in the queue to a new array.</summary> /// <returns>A new array containing a snapshot of elements copied from the queue.</returns> public TValue[] ToArray() { lock (_syncLock) { var clonedHeap = new MinBinaryHeap(_minHeap); return(clonedHeap.Items.Select(x => x.Value).ToArray()); } }
/// <summary> /// Checks whether the heap is a proper Min heap. /// </summary> /// <typeparam name="TKey">Type of the keys stored in the heap. </typeparam> /// <typeparam name="TValue">Type of the values stored in the heap. </typeparam> /// <param name="arraySize">Size of the heap array. </param> /// <param name="heap">A Min binary heap. </param> /// <returns>True if the heap is a proper Min binary heap, and false otherwise. </returns> public static bool HasMinOrderPropertyForHeap <TKey, TValue>(int arraySize, MinBinaryHeap <TKey, TValue> heap) where TKey : IComparable <TKey> { for (int i = 0; i < arraySize; i++) { HasMinOrderPropertyForNode(heap, i); } return(true); }
public void MinBinaryHeapSizeTest() { MinBinaryHeap <int, int> heap = new MinBinaryHeap <int, int>(); Assert.AreEqual(0, heap.Size); heap.Insert(1, 11); heap.Insert(2, 22); Assert.AreEqual(2, heap.Size); }
public void BuildHeap_Iteratively() { var heap = new MinBinaryHeap <int, string>(_keyValues); heap.BuildHeap_Iteratively(heap.HeapArray.Count); Assert.AreEqual(9, heap.HeapArray.Count); Assert.IsTrue(HasMinOrderPropertyForHeap(_keyValues.Count, heap)); }
public void TestMinBinaryHeap() { MinBinaryHeap mbh = new MinBinaryHeap(); TestInsert(mbh, HeapType.MIN_HEAP); mbh = new MinBinaryHeap(); TestRemove(mbh, HeapType.MIN_HEAP); }
public void MinBinaryHeapConstructorTest() { var minHeapDefault = new MinBinaryHeap <string, int>(); var minHeapCustom = new MinBinaryHeap <string, int>(16); Assert.NotNull(minHeapDefault); Assert.NotNull(minHeapCustom); Assert.AreEqual(32, minHeapDefault.Capacity); Assert.AreEqual(32, minHeapDefault.Capacity); }
public void MinValueElementIsOnTheTop() { var sut = new MinBinaryHeap <int>(); sut.Insert(20); sut.Insert(10); Assert.Equal(10, sut.GetTop()); Assert.Equal(20, sut.GetTop()); }
public void AddTest() { _minHeap = new MinBinaryHeap <int>(); for (int i = 0; i < _intArray.Length; i++) { _minHeap.Add(_intArray[i]); Assert.AreEqual(_minHeap.Count, i + 1); } }
public void CreateFromIEnumerableTest() { IEnumerable <int> enumerable = _intArray.AsEnumerable(); _minHeap = new MinBinaryHeap <int>(enumerable); int[] heapCopy = new int[_minHeap.Count]; _minHeap.CopyTo(heapCopy, 0); CollectionAssert.AreEquivalent(_intArray, heapCopy); Assert.AreEqual(_intArray.Length, _minHeap.Count); }
public Path CalculatePath(Vector2 startPoint, Vector2 endPoint) { PathNode startNode = _grid.GetValue(startPoint); PathNode endNode = _grid.GetValue(endPoint); bool isFound = false; PathNode[] pathNodes = null; if (endNode.IsObstacle) { endNode = TryFindOptimalNeighbour(startNode, endNode); if (endNode == null) { return(new Path(null, false)); } } _openSet = new MinBinaryHeap <PathNode>(); _closedSet = new HashSet <PathNode>(); _openSet.Add(startNode); while (_openSet.HeapSize > 0) { PathNode currentNode = _openSet.RemoveFirst(); _closedSet.Add(currentNode); if (currentNode == endNode) { pathNodes = RetracePath(startNode, endNode); if (pathNodes.Length > 0) { isFound = true; } break; } if (currentNode.Neighbours == null) { currentNode.SetNeighbours(GetNeighbours(currentNode)); } foreach (PathNode neighbour in currentNode.Neighbours) { if (_closedSet.Contains(neighbour)) { continue; } CheckNeighbour(currentNode, neighbour, endNode); } } return(new Path(pathNodes, isFound)); }
public Optional <IEnumerable <WeightedEdge <T> > > FindSpanningTreeEdges(IGraph <T> graph) { if (graph == null) { throw new ArgumentNullException(nameof(graph)); } if (graph.Count == 0) { return(Optional <IEnumerable <WeightedEdge <T> > > .None()); } var source = _sourceNodeProvider(graph); var distances = InitializeDistanceTable(graph, source); var verticesToProcess = new MinBinaryHeap <DistanceInfo <T> >(DistanceInfo <T> .DistanceComparer); var processedVertices = new HashSet <T>(graph.Comparer); var spanningTree = new HashSet <WeightedEdge <T> >(WeightedEdge <T> .NonDirectionalComparer(graph.Comparer)); verticesToProcess.Push(DistanceInfo <T> .Zero(source)); while (verticesToProcess.Count > 0) { var currentVertex = verticesToProcess.Pop().Single().PreviousVertex; var sourceDistance = distances[currentVertex]; processedVertices.Add(currentVertex); if (graph.Comparer.Equals(source, currentVertex) == false) { var edge = new WeightedEdge <T>(sourceDistance.PreviousVertex, currentVertex, sourceDistance.Distance); if (spanningTree.Contains(edge) == false) { spanningTree.Add(edge); } } foreach (var destinationVertex in graph.GetAdjacentVertices(currentVertex)) { if (processedVertices.Contains(destinationVertex)) { continue; } var step = StepMetadata <T> .ForSpanningTree(currentVertex, destinationVertex, distances); if (step.FoundShorterDistance()) { distances[destinationVertex] = step.ToSource(); verticesToProcess.Push(step.ToDestination()); } } } return(spanningTree); }
public static List <GraphNode <TValue> > GetShortestDistancesFromRoot <TValue>(GraphNode <TValue> startNode) { //1- Get the list of all vertexes in the graph . List <GraphNode <TValue> > bfsOrdering = BFS.BFS_Iterative(startNode); /* Extra space usage O(V) for bfsOrdering. */ //2- Set the distance of all the nodes from the root node to infinite. foreach (GraphNode <TValue> node in bfsOrdering) { node.DistanceFromStartNode = int.MaxValue; // aka. Infinite. } //3- Set the distance of the root node from the root node to zero. startNode.DistanceFromStartNode = 0; //4- Build a MinHeap over all the nodes in the array. var minHeap = new MinBinaryHeap <GraphNode <TValue>, TValue>(bfsOrdering.Select(o => new KeyValuePair <GraphNode <TValue>, TValue>(o, o.Value)).ToList()); /* Extra space usage O(V) for heapArray. */ var shortestDistanceFromRoot = new List <GraphNode <TValue> >(); /* Extra space usage O(V) for tracking shortest distances of all the nodes from the root node. */ while (true) // Repeat until minHeap is empty. { //5- Update the distance of all the adjacent nodes of the current minimum node. if (minHeap.TryFindRoot(out KeyValuePair <GraphNode <TValue>, TValue> currentMinNode, minHeap.HeapArray.Count)) { foreach (GraphEdge <TValue> edge in currentMinNode.Key.Adjacents) { if (!shortestDistanceFromRoot.Contains(edge.Node)) { if (edge.Node.DistanceFromStartNode > currentMinNode.Key.DistanceFromStartNode + edge.Weight) { edge.Node.DistanceFromStartNode = currentMinNode.Key.DistanceFromStartNode + edge.Weight; int index = minHeap.FindIndex(edge.Node); /* Can be O(1) if the index of each element is stored with the element. */ if (index >= 0) { minHeap.BubbleUp_Iteratively(index, minHeap.HeapArray.Count); } } } } if (minHeap.TryRemoveRoot(out currentMinNode, minHeap.HeapArray.Count)) { shortestDistanceFromRoot.Add(currentMinNode.Key); } else { break; } } else { break; } } return(shortestDistanceFromRoot); }
public void MinBinaryHeapGetMinimumValueTest() { MinBinaryHeap <int, int> heap = new MinBinaryHeap <int, int>(); heap.Insert(2, 22); heap.Insert(1, 11); heap.Insert(3, 33); Assert.AreEqual(3, heap.Size); Assert.AreEqual(11, heap.GetMinimumValue()); Assert.AreEqual(3, heap.Size); }
public void MinBinaryHeapIsEmptyTest() { MinBinaryHeap <int, int> heap = new MinBinaryHeap <int, int>(); Assert.IsTrue(heap.IsEmpty); heap.Insert(1, 1); heap.Insert(2, 2); Assert.IsFalse(heap.IsEmpty); heap.Clear(); Assert.IsTrue(heap.IsEmpty); }
/// <summary>Copies the elements stored in the queue to a new array.</summary> /// <returns>A new array containing a snapshot of elements copied from the queue.</returns> public KeyValuePair <TKey, TValue>[] ToArray() { var clonedHeap = new MinBinaryHeap(_minHeap); var result = new KeyValuePair <TKey, TValue> [_minHeap.Count]; for (int i = 0; i < result.Length; i++) { result[i] = clonedHeap.Remove(); } return(result); }
public void DescendingSortInplaceCorrect(string input) { // Arrange var inputArray = input.Split(' ').Select(int.Parse).ToArray(); var expectArray = inputArray.OrderByDescending(x => x).ToArray(); // Act MinBinaryHeap <int> .HeapSort(inputArray, inputArray.Length); // Assert Assert.AreEqual(expectArray, inputArray); }
public void BuildHeapOptimalSwaps(int inputCount, string input, int expCount, string[] expSwaps) { // Arrange var inputArray = input.Split(' ').Select(int.Parse).ToArray(); var log = new List <string>(); // Act var minBinHeap = new MinBinaryHeap <int>(inputArray, log); // Assert Assert.AreEqual(expCount, minBinHeap.Log.Count); Assert.AreEqual(expSwaps, minBinHeap.Log.ToArray()); }
public MinBinaryHeap <int, int> TestMinHeap() { var values = new List <int>() { 3, 7, 10, 1, 4, 4, 0, 20, 15, 12 }; var minHeap = new MinBinaryHeap <int, int>(values.Count); values.ForEach(v => minHeap.Add(v, v)); return(minHeap); }
/// <summary> /// Copies the elements stored in the queue to a new array. /// </summary> /// <returns> /// A new array containing a snapshot of elements copied from /// the queue. /// </returns> public ValueTuple <T, V>[] ToArray() { lock (_syncLock) { var clonedHeap = new MinBinaryHeap(_minHeap); var result = new ValueTuple <T, V> [_minHeap.Count]; for (var i = 0; i < result.Length; i++) { result[i] = clonedHeap.Remove(); } return(result); } }
/// <summary> /// Copies the elements stored in the queue to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the queue.</returns> public KeyValuePair <TKey, TValue>[] ToArray() { lock (this._syncLock) { var clonedHeap = new MinBinaryHeap(this._minHeap); var result = new KeyValuePair <TKey, TValue> [this._minHeap.Count]; for (var i = 0; i < result.Length; i++) { result[i] = clonedHeap.Remove(); } return(result); } }
public void AddFollowedByPopTest() { _minHeap = new MinBinaryHeap <int>(); for (int i = 0; i < _intArray.Length; i++) { _minHeap.Add(_intArray[i]); Assert.IsTrue(_minHeap.Count == 1); Assert.IsTrue(_minHeap.Pop(out int top)); Assert.AreEqual(top, _intArray[i]); Assert.IsTrue(_minHeap.Count == 0); } }
public MinimumSpanningTree GetMst() { var selectedItems = new List<Edge>(); var source = new MinBinaryHeap<Edge>(_edges); var mark = 1; while (source.Count > 0) { var element = source.GetTopElement(); source.DeleteTopElement(); if (!CycleFound(selectedItems, element)) { selectedItems.Add(element); var localMark = mark; var foundEdge = selectedItems.Where( edge => edge.From.Number == element.From.Number || edge.To.Number == element.From.Number || edge.From.Number == element.To.Number || edge.To.Number == element.To.Number) .Where(edge => edge.From != element.From && edge.To != element.To) .ToArray(); var mrkItems = foundEdge.Where(edge => edge.From.AddedMark > 0).ToArray(); if (mrkItems.Any()) { localMark = mrkItems.Min(edge => edge.From.AddedMark); } var edges = selectedItems.Where(edge => edge.ContainsPoint(element.From, element.To)); foreach (var edge in edges) { edge.State = localMark; } element.State = localMark; mark++; } } return new MinimumSpanningTree(selectedItems.SelectMany(edge => new[] {edge.From, edge.To}).Distinct().ToArray(), selectedItems.Sum(edge => edge.Weight)); }
public static Graph Build(string[] file) { if (file.Length < 1) throw new ArgumentException("No info in file!"); var count = int.Parse(file[0]); if (file.Length < count + 1) throw new ArgumentException("Wrong lines count!"); var points = Enumerable.Range(0, count).Select(i => new Point(i)).ToArray(); var edges = new MinBinaryHeap<Edge>(); for (var i = 1; i < count + 1; i++) { var positions = file[i].Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)) .ToArray(); foreach (var positionInString in positions) { var position = int.Parse(positionInString[0]); var weight = int.Parse(positionInString[1]); var from = points[i - 1]; var to = points[position]; if (!edges.Any(edge => edge.ContainsPoints(from, to))) { edges.Add(new Edge(from, to, weight)); } } } return new Graph(edges, count, points); }