public void DeleteMinTest() { // Heap FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>(); // Add collection of nodes HeapNode <float, char> node2 = heap.Insert(7, 'b'); HeapNode <float, char> node1 = heap.Insert(3, 'a'); HeapNode <float, char> node3 = heap.Insert(14, 'c'); HeapNode <float, char> node4 = heap.Insert(35, 'd'); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum, node1); Assert.AreEqual(heap.Minimum.Priority, 3); Assert.AreEqual(heap.Minimum.Value, 'a'); Assert.AreEqual(heap.Count, 4); // Remove minimum element heap.DeleteMin(); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum, node2); Assert.AreEqual(heap.Minimum.Priority, 7); Assert.AreEqual(heap.Minimum.Value, 'b'); Assert.AreEqual(heap.Count, 3); }
public void FibonacciHeapPeekTest() { // small heap FibonacciHeap <Int32, String> heap = new FibonacciHeap <Int32, String>(); heap.Insert(0, "0"); heap.Peek.ShouldBe("0"); heap.Insert(1, "1"); heap.Peek.ShouldBe("0"); heap.Insert(-1, "-1"); heap.Peek.ShouldBe("-1"); // large heap heap = new FibonacciHeap <Int32, String>(); for (Int32 index = 0; index < this.values.Length; index++) { heap.Insert(this.values[index].Key, this.values[index].Value); heap.Peek.ShouldBe(heap.Min(item => item.Key).ToString()); heap.Peek.ShouldBe(this.values.Take(index + 1).Min(item => item.Key).ToString()); } // exceptions heap = new FibonacciHeap <Int32, String>(); String peek; Should.Throw <InvalidOperationException>(() => peek = heap.Peek); }
public void DecreasePriorityTest() { // Heap FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>(); // Add collection of nodes HeapNode <float, char> node2 = heap.Insert(7, 'b'); HeapNode <float, char> node1 = heap.Insert(3, 'a'); HeapNode <float, char> node3 = heap.Insert(14, 'c'); HeapNode <float, char> node4 = heap.Insert(35, 'd'); // Decrease priority of node heap.DecreasePriority(node4, 1); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum.Priority, 1); Assert.AreEqual(heap.Minimum.Value, 'd'); Assert.AreEqual(heap.Minimum, node4); Assert.AreEqual(heap.Count, 4); // Delete min so trees are consolidated heap.DeleteMin(); // Decrease priority of node heap.DecreasePriority(node2, 0); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum, node2); Assert.AreEqual(heap.Minimum.Priority, 0); Assert.AreEqual(heap.Minimum.Value, 'b'); Assert.AreEqual(heap.Count, 3); }
public void InsertTest() { // Heap FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>(); // Add collection of nodes HeapNode <float, char> node2 = heap.Insert(7, 'b'); HeapNode <float, char> node1 = heap.Insert(3, 'a'); HeapNode <float, char> node3 = heap.Insert(14, 'c'); HeapNode <float, char> node4 = heap.Insert(35, 'd'); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum, node1); Assert.AreEqual(heap.Minimum.Priority, 3); Assert.AreEqual(heap.Minimum.Value, 'a'); Assert.AreEqual(heap.Count, 4); // Insert new minimum HeapNode <float, char> node5 = heap.Insert(2, 'e'); // Check minimum is correct, and contains correct values Assert.AreEqual(heap.Minimum, node5); Assert.AreEqual(heap.Minimum.Priority, 2); Assert.AreEqual(heap.Minimum.Value, 'e'); Assert.AreEqual(heap.Count, 5); }
/// <summary> /// Implementation of uniform-cost search algorithm using a Fibonacci heap data structure to minimize computing times /// </summary> /// <param name="source">The node on which to start the search</param> /// <param name="destination">The node we try to find the shortest path to, starting from source</param> public List <int> LeastCostPath(int source, int destination) { var Predecessor = new Dictionary <int, int>(); var Distance = new Dictionary <int, double>(); var Frontier = new FibonacciHeap <int, double>(0); Frontier.Insert(new FibonacciHeapNode <int, double>(source, 0)); var Explored = new List <int>(); Predecessor.Add(source, -1); //value of -1 indicates this node has no predecessors while (true) { if (Frontier.IsEmpty()) { throw new Exception("LeastCostPath: Failed to find path between source (" + source + ") and destination (" + destination + ")."); } var minNode = Frontier.RemoveMin(); if (minNode.Data == destination) { List <int> LCP = new List <int> { minNode.Data }; int pred = Predecessor[minNode.Data]; while (pred != -1) { LCP.Add(pred); pred = Predecessor[pred]; } LCP.Reverse(); return(LCP); } Explored.Add(minNode.Data); foreach (int neighbor in this.GetNeighbors(minNode.Data)) { if (!Explored.Contains(neighbor)) { var neighborCost = minNode.Key + AdjacencyMatrix[minNode.Data, neighbor]; Frontier.Insert(new FibonacciHeapNode <int, double>(neighbor, neighborCost)); if (Distance.TryGetValue(neighbor, out double cost)) { if (neighborCost < cost) { Predecessor[neighbor] = minNode.Data; Distance[neighbor] = neighborCost; } } else { Predecessor.Add(neighbor, minNode.Data); Distance.Add(neighbor, neighborCost); } } } } }
public void TestMinimum() { FibonacciHeap <int, double> heap = new FibonacciHeap <int, double>(); heap.Insert(0, 0.9); heap.Insert(1, 17.9); heap.Insert(2, 0.333); heap.Insert(3, 2.7); heap.Insert(4, 42); Assert.AreEqual(2, heap.Minimum); }
public void Min_FibonacciHeap_Test() { int nodeCount = 1000 * 10; var minHeap = new FibonacciHeap <int>(); for (int i = 0; i <= nodeCount; i++) { minHeap.Insert(i); } for (int i = 0; i <= nodeCount; i++) { minHeap.UpdateKey(i, i - 1); } int min = 0; for (int i = 0; i <= nodeCount; i++) { min = minHeap.Extract(); Assert.AreEqual(min, i - 1); } //IEnumerable tests. Assert.AreEqual(minHeap.Count, minHeap.Count()); var rnd = new Random(); var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(x => rnd.Next()).ToList(); foreach (var item in testSeries) { minHeap.Insert(item); } for (int i = 0; i < testSeries.Count; i++) { var decremented = testSeries[i] - rnd.Next(0, 1000); minHeap.UpdateKey(testSeries[i], decremented); testSeries[i] = decremented; } testSeries.Sort(); for (int i = 0; i < nodeCount - 2; i++) { min = minHeap.Extract(); Assert.AreEqual(testSeries[i], min); } //IEnumerable tests. Assert.AreEqual(minHeap.Count, minHeap.Count()); }
/// <summary> /// Uses A*-algorithm to find the best route between two tiles. /// </summary> /// <param name="start">First tile to search from.</param> /// <param name="goal">Goal to find.</param> /// <param name="previous">Tile just before the first tile.</param> /// <param name="forbidden">List of tiles that should be never used on route.</param> /// <param name="sign">Optional function for building signs.</param> /// <returns></returns> internal static List <PathInfo> FindPath(TileIndex start, TileIndex goal, TileIndex previous, HashSet <TileIndex> forbidden = null, Action <TileIndex, string> sign = null) { // Nodes to evaluate var tilesToProcess = new FibonacciHeap <TileIndex>(); tilesToProcess.Insert(start, 0); // Nodes evaluated var cameFrom = new Dictionary <TileIndex, PathInfo>(); cameFrom[start] = new PathInfo(start, 1, 0, BuildType.Basic, previous != null ? new PathInfo(previous, 1, 0, BuildType.Basic, null) : null); while (tilesToProcess.Count() > 0) { var current = tilesToProcess.Pop(); //AILog.Info($"Processing: {Helper.FormatTile(current)}"); if (current == goal) { // We found the target. return(RoadBuilder.BuildFinalPath(cameFrom[current])); } var neighbors = RoadBuilder.GetNeighbors(current, cameFrom[current]); foreach (var neighborItem in neighbors) { var neighbor = neighborItem.Tile; if ((neighbor == previous) || ((forbidden != null) && forbidden.Contains(neighbor))) { // We can't go here. continue; } var neighborDist = neighborItem.Length; if (!cameFrom.ContainsKey(neighbor)) { tilesToProcess.Insert(neighbor, neighborItem.Cost); } else { if (neighborItem.Cost >= cameFrom[neighbor].Cost) { continue; } } sign?.Invoke(neighbor, neighborItem.Cost.ToString()); cameFrom[neighbor] = neighborItem; } } return(null); }
public void Max_FibonacciHeap_Test() { int nodeCount = 1000 * 10; var maxHeap = new FibonacciHeap <int>(SortDirection.Descending); for (int i = 0; i <= nodeCount; i++) { maxHeap.Insert(i); } for (int i = 0; i <= nodeCount; i++) { maxHeap.UpdateKey(i, i + 1); } int max = 0; for (int i = nodeCount; i >= 0; i--) { max = maxHeap.Extract(); Assert.AreEqual(max, i + 1); } //IEnumerable tests. Assert.AreEqual(maxHeap.Count, maxHeap.Count()); var rnd = new Random(); var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(x => rnd.Next()).ToList(); foreach (var item in testSeries) { maxHeap.Insert(item); } for (int i = 0; i < testSeries.Count; i++) { var incremented = testSeries[i] + rnd.Next(0, 1000); maxHeap.UpdateKey(testSeries[i], incremented); testSeries[i] = incremented; } testSeries = testSeries.OrderByDescending(x => x).ToList(); for (int i = 0; i < nodeCount - 2; i++) { max = maxHeap.Extract(); Assert.AreEqual(testSeries[i], max); } //IEnumerable tests. Assert.AreEqual(maxHeap.Count, maxHeap.Count()); }
public void FibonacciHeapUpdateKeyMinHeap() { FibonacciHeap <HeapElement> heap = new FibonacciHeap <HeapElement>((a, b) => a.Priority.CompareTo(b.Priority), true); FillHeap(heap, 100); Assert.AreEqual(100, heap.Count); // add new element. Give it a priority of 50 HeapElement element = new HeapElement(50, "Value: 50"); heap.Insert(element); Assert.AreEqual(101, heap.Count); // update key to 10, using an action lambda heap.UpdateKey(element, (a, b) => a.Priority = b, 10); Assert.AreEqual(10, element.Priority); // check if the heap is still correct HeapElement previous = heap.ExtractRoot(); HeapElement current = heap.ExtractRoot(); while (current != null) { Assert.IsTrue(previous.Priority <= current.Priority); previous = current; current = heap.ExtractRoot(); } // heap should be empty Assert.AreEqual(0, heap.Count); }
public static void InsertRange <T>(this FibonacciHeap <T> heap, IEnumerable <FibonacciHeapNode <T> > enumerable) { foreach (var item in enumerable) { heap.Insert(item); } }
public IList <ILevelTile> CalculatePath(ILevelTile from, ILevelTile to) { target = to; openNodes = new FibonacciHeap <float>(); closedNodes = new HashSet <AStarNode>(); tilesToNodes = new Dictionary <ILevelTile, AStarNode>(); AStarNode startNode = new AStarNode(from, heuristic.GetDistance(from.CenterPos, to.CenterPos)); startNode.cost = 0; tilesToNodes.Add(from, startNode); openNodes.Insert(startNode); do { AStarNode currNode = (AStarNode)openNodes.ExtractMin(); if (currNode.tile.Equals(to)) { return(GetPathToNode(currNode)); } closedNodes.Add(currNode); ExpandNode(currNode); } while (openNodes.IsEmpty() == false); // No path found return(null); }
public void Insert(T value, TKey key) { var node = new FibonacciHeapNode <T, TKey>(value, key); Heap.Insert(node); HeapLookup.Add(value, node); }
static void TestCase4() { var random = new Random(); var myHeap = new FibonacciHeap<double>(int.MinValue, Comparer<double>.Default); var thirdPartyHeap = new FastPriorityQueue<FastPriorityQueueNode>(1000); for (var i = 0; i < 1000; i++) { if (random.Next(3) == 0 && thirdPartyHeap.Any()) { var myResult = myHeap.ExtractMin(); var otherResult = thirdPartyHeap.Dequeue(); Assert(myResult.Item1); Assert(Math.Abs(myResult.Item2 - otherResult.Priority) < double.Epsilon); } else { var value = random.NextDouble()*10; myHeap.Insert(value); thirdPartyHeap.Enqueue(new FastPriorityQueueNode(), value); } } while (thirdPartyHeap.Any()) { var myResult = myHeap.ExtractMin(); var otherResult = thirdPartyHeap.Dequeue(); Assert(myResult.Item1); Assert(Math.Abs(myResult.Item2 - otherResult.Priority) < double.Epsilon); } }
/// <summary> /// 插入新结点 /// </summary> public void Insert(TElement item, TPriority priority) { FibonacciHeapNode <TElement, TPriority> node = new FibonacciHeapNode <TElement, TPriority>(item, priority); heap.Insert(node); fibonacciNodeDic[item] = node; }
private void GenerateNode(Point tile, double distance, double moveDist, out DijkstraTile outTile, out FibonacciHeapNode <DijkstraTile, double> outNode) { outTile = new DijkstraTile(tile, distance, moveDist); outNode = new FibonacciHeapNode <DijkstraTile, double>(outTile, outTile.Distance); Tiles.Add(tile, outTile); NodeMap.Add(tile, outNode); Heap.Insert(outNode); }
/// <summary> /// Implementation of Yen's algorithm which finds the shortest path between nodes, and then the /// K-1 shortest deviations from this path. Paths returned will be simple and loopless /// </summary> /// <param name="K">The number of shortest paths to find.</param> /// <param name="source">The node on which to start the search</param> /// <param name="destination">The node we try to find the shortest path to, starting from source</param> /// <returns></returns> public List <List <int> > KShortestPaths(int K, int source, int destination) { List <List <int> > ShortestPaths = new List <List <int> >(); var PotentialPaths = new FibonacciHeap <List <int>, double>(0); ShortestPaths.Add(LeastCostPath(source, destination)); //now find next K-1 shortest paths foreach (int k in Enumerable.Range(1, K - 1)) { //The spur node ranges from the first node to the next to last node in the previous k-shortest path. int spurNodeCount = ShortestPaths[k - 1].Count - 1; foreach (int i in Enumerable.Range(0, spurNodeCount)) { int spurNode = ShortestPaths[k - 1][i]; List <int> rootPath = ShortestPaths[k - 1].GetRange(0, i + 1); PSO_WeightedGraph AlteredGraph = this.Clone(); //temporarily remove edges to avoid retracing our steps foreach (List <int> shortPath in ShortestPaths) { if (rootPath.SequenceEqual(shortPath.Take(i + 1))) { AlteredGraph.AdjacencyMatrix[shortPath[i], shortPath[i + 1]] = 0; } } //To avoid looping back over a previous path, we disconnect nodes in the root path (except the spur node) //by setting the weights of the edges that connect them to the graph to 0 foreach (int x in Enumerable.Range(0, Size).Where(a => a != spurNode & rootPath.Contains(a))) { var v = Vector <double> .Build.Sparse(Size); AlteredGraph.AdjacencyMatrix.SetColumn(x, v); AlteredGraph.AdjacencyMatrix.SetRow(x, v); } //build spur path and connect the spur path to the root List <int> spurPath = new List <int>(); //finding the least cost path may fail due to removing the edges above; just ignore and continue try { spurPath = AlteredGraph.LeastCostPath(spurNode, destination); } catch (Exception ex) { break; } List <int> totalPath = rootPath; totalPath.AddRange(spurPath.Where(node => node != spurNode).ToList()); PotentialPaths.Insert(new FibonacciHeapNode <List <int>, double>(totalPath, this.PathCost(totalPath))); } if (PotentialPaths.IsEmpty()) { break; } ShortestPaths.Add(PotentialPaths.RemoveMin().Data); } return(ShortestPaths); }
public static List <Node> Dijkstras(Graph graph, Vector2 sourceVect, Vector2 goalVect) { Node source = null; Node goal = null; Node expandedNode; List <Node> finalizedSet = new List <Node>(); FibonacciHeap <Node, float> prioQueue = new FibonacciHeap <Node, float>(0); foreach (Node node in graph.Nodes) { node.Distance = 1f / 0f; node.SetPredecessor(graph.Nodes, null); if (node.MapPos == sourceVect) { source = node; } else { prioQueue.Insert(new FibonacciHeapNode <Node, float>(node, node.Distance)); } if (node.MapPos == goalVect) { goal = node; } } source.Distance = 0; prioQueue.Insert(new FibonacciHeapNode <Node, float>(source, source.Distance)); while (prioQueue.Size() != 0) { expandedNode = prioQueue.RemoveMin().Data; finalizedSet.Add(expandedNode); foreach (Node node in graph.Adj[expandedNode]) { if (node.Distance > expandedNode.Distance + 1) { node.Distance = expandedNode.Distance + 1; node.SetPredecessor(graph.Nodes, expandedNode); } } } return(BuildPath(graph, source, goal)); }
private void InitHeap() { _nodes = new Dictionary <int, FibonacciNode <int> >(); _heap1 = new FibonacciHeap <int>((a, b) => a < b); _heap2 = new FibonacciHeap <int>((a, b) => a < b); _nodes[3] = _heap1.Insert(3); _nodes[1] = _heap1.Insert(1); _nodes[2] = _heap1.Insert(2); _nodes[5] = _heap2.Insert(5); _nodes[4] = _heap2.Insert(4); _nodes[6] = _heap2.Insert(6); }
public void UnconsolidatedHeapInsertNull_Null() { FibonacciHeap <int> heap = new FibonacciHeap <int>(); IList <int> input = new List <int>() { 0, 28, }; NUnit.Framework.Assert.IsNull(heap.Insert(null)); }
public void ConsolidatedHeapDecreaseKey_CorrectCuts() { FibonacciHeap <int> heap = new FibonacciHeap <int>(); IList <FibonacciNode <int> > input = new List <FibonacciNode <int> >() { new FibonacciNode <int>(0), new FibonacciNode <int>(28), new FibonacciNode <int>(-13), new FibonacciNode <int>(80), new FibonacciNode <int>(3), new FibonacciNode <int>(7), new FibonacciNode <int>(-7), new FibonacciNode <int>(42), new FibonacciNode <int>(-11), new FibonacciNode <int>(12) }; IList <int> expectedElementOrder = new List <int>() { 7, -8, -11, 12, -42, 80, -1, -3, 0 }; foreach (FibonacciNode <int> value in input) { heap.Insert(value); } heap.ExtractMin(); // A decrease key with no structural changes heap.DecreaseKey(input[6], -8); // Normal cuts with parent marked heap.DecreaseKey(input[7], -42); heap.DecreaseKey(input[4], -1); // Double cascading cut heap.DecreaseKey(input[1], -3); IList <int> result = heap.GetAllValues(); for (int i = 0; i < expectedElementOrder.Count; ++i) { NUnit.Framework.Assert.IsTrue(expectedElementOrder[i] == result[i]); } NUnit.Framework.Assert.IsTrue(heap.GetMin() == -42); }
public void UnconsolidatedHeapContainsNode_True() { FibonacciNode <int> node = new FibonacciNode <int>(-3); FibonacciHeap <int> heap = new FibonacciHeap <int>(); IList <int> input = new List <int>() { 0, 28, -13, 80 }; heap.Insert(node); foreach (int value in input) { heap.Insert(value); } NUnit.Framework.Assert.IsTrue(heap.Contains(node)); }
public void Insert(T data, TKey priority) { if (ObjectToHeapNodeMapping.ContainsKey(data)) { throw new ArgumentException("Fibonacci heap can't insert a node it already contains."); } var node = new FibonacciHeapNode <T, TKey>(data, priority); Heap.Insert(node); ObjectToHeapNodeMapping.Add(data, node); }
public void TestBasicFunctionality() { var heap = new FibonacciHeap <int>(); heap.Insert(4, 4); heap.Insert(1, 1); heap.Insert(5, 5); heap.Insert(2, 2); heap.Insert(3, 3); int a = heap.Pop(); int b = heap.Pop(); int c = heap.Pop(); int d = heap.Pop(); int e = heap.Pop(); Assert.AreEqual(1, a); Assert.AreEqual(2, b); Assert.AreEqual(3, c); Assert.AreEqual(4, d); Assert.AreEqual(5, e); }
public void UnconsolidatedHeapDecreaseKeyMinSame_CorrectValue() { FibonacciNode <int> node = new FibonacciNode <int>(-3); FibonacciHeap <int> heap = new FibonacciHeap <int>(); IList <int> input = new List <int>() { 0, 28, -13, 80 }; heap.Insert(node); foreach (int value in input) { heap.Insert(value); } heap.DecreaseKey(node, -4); NUnit.Framework.Assert.IsTrue(heap.GetMin() == -13); }
public void PopTest() { // Heap FibonacciHeap <float, char> heap = new FibonacciHeap <float, char>(); HashSet <float> equalPriorirtyMinimums = new HashSet <float>() { 'b', 'e', 'f', 'g' }; // Check heap starts with no nodes Assert.AreEqual(heap.Count, 0); // Add collection of nodes HeapNode <float, char> node2 = heap.Insert(7, 'b'); HeapNode <float, char> node1 = heap.Insert(3, 'a'); HeapNode <float, char> node3 = heap.Insert(14, 'c'); HeapNode <float, char> node4 = heap.Insert(35, 'd'); HeapNode <float, char> node5 = heap.Insert(7, 'e'); HeapNode <float, char> node6 = heap.Insert(7, 'f'); HeapNode <float, char> node7 = heap.Insert(7, 'g'); // Check heap has correct number of nodes Assert.AreEqual(heap.Count, 7); char minimum = heap.Pop(); // Check returned item is the correct value, and is not still in heap Assert.AreEqual(minimum, 'a'); Assert.AreNotEqual(heap.Minimum.Value, minimum); Assert.AreEqual(heap.Count, 6); // Pop a set of equal priority values, check heap outputs them all (order is undefined) for (int i = 0; i < equalPriorirtyMinimums.Count; i++) { minimum = heap.Pop(); // Check returned item is the correct value, and is not still in heap Assert.IsTrue(equalPriorirtyMinimums.Contains(minimum)); Assert.AreNotEqual(heap.Minimum.Value, minimum); Assert.AreEqual(heap.Count, 5 - i); } minimum = heap.Pop(); // Check returned item is the correct value, and is not still in heap Assert.AreEqual(minimum, 'c'); Assert.AreNotEqual(heap.Minimum.Value, minimum); Assert.AreEqual(heap.Count, 1); minimum = heap.Pop(); // Check returned item is the correct value Assert.AreEqual(minimum, 'd'); Assert.AreEqual(heap.Count, 0); }
public static DijkstraTile[,] Dijkstra(IEnumerable <Point> start, int width, int height, double maxDist, Func <Point, Point, double> length, Func <Point, IEnumerable <Point> > neighbors) { var dijkstraMap = new DijkstraTile[width, height]; var nodeMap = new FibonacciHeapNode <DijkstraTile, double> [width, height]; var heap = new FibonacciHeap <DijkstraTile, double>(0); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Point tile = new Point(x, y); bool isStart = start.Contains(tile); DijkstraTile dTile = new DijkstraTile(tile, isStart ? 0 : double.PositiveInfinity, isStart ? 0 : double.PositiveInfinity); var node = new FibonacciHeapNode <DijkstraTile, double>(dTile, dTile.Distance); dijkstraMap[x, y] = dTile; nodeMap[x, y] = node; heap.Insert(node); } } while (!heap.IsEmpty()) { var node = heap.RemoveMin(); var dTile = node.Data; if (dTile.Distance >= maxDist) { break; } foreach (var neighbor in neighbors(dTile.Tile)) { if (neighbor.X < 0 || neighbor.Y < 0 || neighbor.X >= width || neighbor.Y >= height) { continue; } var nodeNeighbor = nodeMap[neighbor.X, neighbor.Y]; var dNeighbor = nodeNeighbor.Data; double newDist = dTile.Distance + length(dTile.Tile, dNeighbor.Tile); if (newDist < dNeighbor.Distance) { dNeighbor.Distance = newDist; dNeighbor.Previous = dTile; dNeighbor.MoveDistance = dTile.MoveDistance + 1; heap.DecreaseKey(nodeNeighbor, dNeighbor.Distance); } } } return(dijkstraMap); }
public void UnconsolidatedHeapExtractMin_CorrectValue() { FibonacciNode <int> node = new FibonacciNode <int>(-20); FibonacciHeap <int> heap = new FibonacciHeap <int>(); IList <int> input = new List <int>() { 0, 28, -13, 80 }; heap.Insert(node); foreach (int value in input) { heap.Insert(value); } NUnit.Framework.Assert.IsTrue(heap.ExtractMin() == node); NUnit.Framework.Assert.IsTrue(heap.GetMin() == -13); NUnit.Framework.Assert.IsTrue(heap.GetAllValues().Count == input.Count); }
public void min() { var heap = new FibonacciHeap <int, double>(0); var node = new FibonacciHeapNode <int, double>(-1, 0); heap.Insert(node); while (!heap.IsEmpty()) { node = heap.Min(); heap.RemoveMin(); int n = node.Data; double timee = node.Key; if (n == -2) { continue; } var con = parameter[n]; foreach (var item in con) { //ListValueData.Add(item); int n1 = item.Key; // el node el connected beha double t1 = item.Value.Key; // el weight 3ala el edge double oldtime = ans[n1].Value.Key; double dist = item.Value.Value.Key; if (t1 + timee < oldtime) { var vip = new KeyValuePair <int, KeyValuePair <double, double> >(n, new KeyValuePair <double, double>(t1 + timee, dist)); ans[n1] = vip; var node2 = new FibonacciHeapNode <int, double>(n1, t1 + timee); heap.Insert(node2); } } } }
public void FibonacciHeapInsertTest() { FibonacciHeap <Int32, String> heap = new FibonacciHeap <Int32, String>(); heap.Insert(this.values[0].Key, this.values[0].Value); heap.Peek.ShouldBe(this.values[0].Value); heap.Count.ShouldBe(1); heap.Insert(this.values[1].Key, this.values[1].Value); heap.Insert(this.values[2].Key, this.values[2].Value); heap.Insert(this.values[3].Key, this.values[3].Value); heap.Count.ShouldBe(4); heap.Insert(this.values[4].Key, this.values[4].Value); heap.Count.ShouldBe(5); // exceptions Should.Throw <ArgumentNullException>(() => new FibonacciHeap <String, String>().Insert(null, null)); }
public void TestDecreaseKey() { // Build heap FibonacciHeap <int, double> heap = new FibonacciHeap <int, double>(); heap.Insert(0, 0.9); heap.Insert(1, 17.9); heap.Insert(2, 0.333); heap.Insert(3, 2.7); heap.Insert(4, 42); // Force tree consolidation by removing one node heap.ExtractMinimum(); // Decrease key and check result heap.DecreaseKey(3, 0.5); Assert.AreEqual(3, heap.Minimum); Assert.AreEqual(4, heap.Count); // Extract min element again heap.ExtractMinimum(); Assert.AreEqual(0, heap.Minimum); }
static void Main(string[] args) { var heap = new FibonacciHeap<int, int>(); heap.Insert(3, 3); heap.Insert(8, 8); heap.Insert(9, 9); heap.Insert(11, 11); heap.Insert(14, 14); heap.Insert(38, 38); heap.Insert(38, 49); heap.Insert(3, 56); heap.Insert(38, 18); heap.Insert(38, 17); heap.Insert(3, 4); //heap.Insert(3, 3); //heap.Insert(8, 8); //heap.Insert(9, 9); //heap.Insert(11, 11); //heap.Insert(14, 14); //heap.Insert(38, 38); //heap.Insert(49, 49); //heap.Insert(56, 56); //heap.Insert(18, 18); //heap.Insert(17, 17); //heap.Insert(4, 4); int len = heap.Count; for (int i = 0; i < len; i++) { var min = heap.DeleteMin(); Console.WriteLine(min); } }
public void FibonacciHeapUpdateKeyMinHeap() { FibonacciHeap<HeapElement> heap = new FibonacciHeap<HeapElement>((a, b) => a.Priority.CompareTo(b.Priority), true); FillHeap(heap, 100); Assert.AreEqual(100, heap.Count); // add new element. Give it a priority of 50 HeapElement element = new HeapElement(50, "Value: 50"); heap.Insert(element); Assert.AreEqual(101, heap.Count); // update key to 10, using an action lambda heap.UpdateKey(element, (a, b) => a.Priority = b, 10); Assert.AreEqual(10, element.Priority); // check if the heap is still correct HeapElement previous = heap.ExtractRoot(); HeapElement current = heap.ExtractRoot(); while(current != null) { Assert.IsTrue(previous.Priority <= current.Priority); previous = current; current = heap.ExtractRoot(); } // heap should be empty Assert.AreEqual(0, heap.Count); }
private static FibonacciHeap<int> CreateHeap(params int[] values) { var heap = new FibonacciHeap<int>(int.MinValue, Comparer<int>.Default); foreach(var value in values) heap.Insert(value); return heap; }