Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PathingAStar"/> class.
 /// </summary>
 /// <param name="heapInitialSize">Initial size of the heap.</param>
 /// <param name="moveCostProvider">The move cost provider.</param>
 /// <param name="pathSmoother">The path smoother to use.</param>
 public PathingAStar(int heapInitialSize, IMoveCost moveCostProvider, ICellCostStrategy cellCostStrategy, ISmoothPaths pathSmoother)
     : base(moveCostProvider, cellCostStrategy, pathSmoother)
 {
     _openSet = new BinaryHeap<IPathNode>(heapInitialSize, new PathNodeComparer());
     _expandedSet = new List<IPathNode>();
     _successorArray = new DynamicArray<IPathNode>(15);
 }
        private static void Dijkstra(Node source, Dictionary<Node, List<Edge>> graph)
        {
            var queue = new BinaryHeap<Node>();

            foreach (Node node in graph.Keys)
            {
                node.Reliability = double.NegativeInfinity;
            }

            source.Reliability = 100.0;
            queue.Insert(source);

            while (queue.Count != 0)
            {
                Node current = queue.ExtractMax();

                if (double.IsNegativeInfinity(current.Reliability))
                {
                    break;
                }

                foreach (var childEdge in graph[current])
                {
                    var newReliability = (current.Reliability * childEdge.Percentage) / 100;
                    //Node nextNode = graph.Keys.FirstOrDefault(n => n.Id == childEdge.EndNode);
                    if (newReliability > childEdge.Node.Reliability)
                    {
                        childEdge.Node.Reliability = newReliability;
                        childEdge.Node.PreviousNode = current;
                        queue.Insert(childEdge.Node);
                    }
                }
            }
        }
Exemplo n.º 3
0
        static void Main()
        {
            BinaryHeap<int> maxPriorityQueue = new BinaryHeap<int>(5);
            maxPriorityQueue.Insert(4);
            maxPriorityQueue.Insert(1);
            maxPriorityQueue.Insert(2);
            maxPriorityQueue.Insert(5);
            maxPriorityQueue.Insert(3);

            Console.WriteLine("Max first (default): ");
            while (maxPriorityQueue.Size > 0)
            {
                Console.WriteLine(maxPriorityQueue.Pop());
            }

            BinaryHeap<int> minPriorityQueue = new BinaryHeap<int>(5, MinIntCompare);

            minPriorityQueue.Insert(4);
            minPriorityQueue.Insert(1);
            minPriorityQueue.Insert(2);
            minPriorityQueue.Insert(5);
            minPriorityQueue.Insert(3);

            Console.WriteLine("Min first (custom comparison passed):");
            while (minPriorityQueue.Size > 0)
            {
                Console.WriteLine(minPriorityQueue.Pop());
            }
        }
Exemplo n.º 4
0
 public void BinaryHeapEmptied()
 {
     BinaryHeap<int> h = new BinaryHeap<int>();
     h.Push(5);
     Assert.AreEqual(5, h.Pop());
     h.Pop();
 }
    static void Main(string[] args)
    {
        spannngTreeEdges = new BinaryHeap<Edge>();
        spanningTreeNodes = new HashSet<int>();
        var graph = BuildGraph();

        // Start Prim's algorithm from each node not still in the spanning tree
        while (spannngTreeEdges.Count > 0)
        {
            var edge = spannngTreeEdges.ExtractMin();
            if (!spanningTreeNodes.Contains(edge.StartNode) || !spanningTreeNodes.Contains(edge.EndNode))
            {
                Prim(graph, edge);
            }
        }

        addedSpanningTreeEdges.Sort();
        foreach (var edge in addedSpanningTreeEdges)
        {
            Console.WriteLine("{{{0}, {1}}} -> {2}", edge.StartNode, edge.EndNode, edge.Weight);
        }

        Console.WriteLine("Budget used: " +
            addedSpanningTreeEdges.Sum(e => e.Weight));
    }
Exemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PathingAStar"/> class.
 /// </summary>
 /// <param name="heapInitialSize">Initial size of the heap.</param>
 public PathingAStar(int heapInitialSize)
     : base(new DiagonalDistance(10), new DefaultCellCostStrategy(), new PathSmoother())
 {
     _openSet = new BinaryHeap<IPathNode>(heapInitialSize, new PathNodeComparer());
     _expandedSet = new List<IPathNode>();
     _successorArray = new DynamicArray<IPathNode>(15);
 }
        public void EmptyHeap_InsertElements_ExtractAllElements_ShouldReturnElementsSorted()
        {
            // Arrange
            var arr = new int[] { 3, 4, -1, 15, 2, 77, -3, 4, 12 };
            //var arr = new int[] { 2, 7, 26, 25, 19, 17, 1, 90, 3, 36 };

            // Act
            var heap = new BinaryHeap<int>();

            foreach (var num in arr)
            {
                heap.Insert(num);
            }

            var elements = new List<int>();
            while (heap.Count > 0)
            {
                var maxElement = heap.ExtractMax();
                elements.Add(maxElement);
            }

            // Assert
            var expected = new int[] { 77, 15, 12, 4, 4, 3, 2, -1, -3 };
            //var expected = new int[] { 90, 36, 26, 25, 19, 17, 7, 3, 2, 1 };
            CollectionAssert.AreEqual(expected, elements);
        }
Exemplo n.º 8
0
        public void BinaryHeapMergeTestMaxHeaps()
        {
            // create two maxheaps based on the priority value of the elements.
            BinaryHeap<HeapElement> heap1 = new BinaryHeap<HeapElement>((a, b) => a.Priority.CompareTo(b.Priority), false);
            BinaryHeap<HeapElement> heap2 = new BinaryHeap<HeapElement>((a, b) => a.Priority.CompareTo(b.Priority), false);

            FillHeap(heap1, 100);
            FillHeap(heap2, 100);
            Assert.AreEqual(100, heap1.Count);
            Assert.AreEqual(100, heap2.Count);
            // merge heap1 into heap2. heap2 will be empty afterwards
            heap1.Merge(heap2);
            Assert.AreEqual(200, heap1.Count);
            Assert.AreEqual(0, heap2.Count);

            // check if they are inserted correctly
            HeapElement previous = heap1.ExtractRoot();
            HeapElement current = heap1.ExtractRoot();
            while(current != null)
            {
                Assert.IsTrue(previous.Priority >= current.Priority);
                previous = current;
                current = heap1.ExtractRoot();
            }
            // heap1 should be empty as well
            Assert.AreEqual(0, heap1.Count);
        }
Exemplo n.º 9
0
        public static int[] Sort(int[] arr, int k)
        {
            int[] result = new int[arr.Length];
            int resultIndex = 0;
            BinaryHeap<int> heap = new BinaryHeap<int>();

            // add k items into heap
            for (int i = 0; i < k && i < arr.Length; ++i)
            {
                heap.Insert(arr [i]);
            }

            // add and remove
            for (int i = k; i < arr.Length; ++i)
            {
                heap.Insert(arr [i]);
                result [resultIndex++] = heap.RemoveRoot();
            }

            // remove remaining
            while (heap.Count > 0)
                result [resultIndex++] = heap.RemoveRoot();

            return result;
        }
    private static void Prim(Dictionary<string, List<Edge>> graph, 
        HashSet<string> spanningTreeNodes, string startNode,
        List<Edge> spannngTreeEdges)
    {
        // Append the startNode child edges to the priority queue
        var priorityQueue = new BinaryHeap<Edge>();
        foreach (var childEdge in graph[startNode])
        {
            priorityQueue.Enqueue(childEdge);
        }
        spanningTreeNodes.Add(startNode);

        while (priorityQueue.Count > 0)
        {
            var smallestEdge = priorityQueue.ExtractMin();
            if (spanningTreeNodes.Contains(smallestEdge.StartNode) ^
                spanningTreeNodes.Contains(smallestEdge.EndNode))
            {
                // Attach the smallest edge to the minimum spanning tree (MST)
                spannngTreeEdges.Add(smallestEdge);
                var nonTreeNode = spanningTreeNodes.Contains(smallestEdge.StartNode) ?
                    smallestEdge.EndNode : smallestEdge.StartNode;
                spanningTreeNodes.Add(nonTreeNode);
                foreach (var childEdge in graph[nonTreeNode])
                {
                    // tuka moje da se optimizira, tai kato ste vkara i niakoi nodove, koito veche sa vkarani v priorityQueue
                    if (spannngTreeEdges.Contains(childEdge))
                    {
                       continue;
                    }
                    priorityQueue.Enqueue(childEdge);
                }
            }
        }
    }
Exemplo n.º 11
0
    static void Main()
    {
        Console.WriteLine("Created an empty heap.");
        var heap = new BinaryHeap<int>();
        heap.Insert(5);
        heap.Insert(8);
        heap.Insert(1);
        heap.Insert(3);
        heap.Insert(12);
        heap.Insert(-4);

        Console.WriteLine();
        Console.WriteLine("Heap elements (max to min):");
        while (heap.Count > 0)
        {
            var max = heap.ExtractMax();
            Console.WriteLine(max);
        }

        var arr = new int[] { 3, 4, -1, 15, 2, 77, -3, 4, 12};
        var heapFromArr = new BinaryHeap<int>(arr);
        Console.WriteLine("Created a heap from array.");

        Console.WriteLine();
        Console.WriteLine("Heap elements (max to min):");
        while (heapFromArr.Count > 0)
        {
            var max = heapFromArr.ExtractMax();
            Console.WriteLine(max);
        }
    }
    private static void Prim(Dictionary<string, List<Edge>> graph, 
        HashSet<string> spanningTreeNodes, string startNode,
        List<Edge> spannngTreeEdges)
    {
        spanningTreeNodes.Add(startNode);
        var priorityQueue = new BinaryHeap<Edge>();
        foreach (var edge in graph[startNode])
        {
            priorityQueue.Enqueue(edge);
        }

        while (priorityQueue.Count > 0)
        {
            var smallestEdge = priorityQueue.ExtractMin();
            if (spanningTreeNodes.Contains(smallestEdge.StartNode) ^
                spanningTreeNodes.Contains(smallestEdge.EndNode))
            {
                var nonTreeNode = spanningTreeNodes.Contains(smallestEdge.StartNode)
                    ? smallestEdge.EndNode
                    : smallestEdge.StartNode;
                spannngTreeEdges.Add(smallestEdge);
                spanningTreeNodes.Add(nonTreeNode);
                foreach (Edge newEdge in graph[nonTreeNode])
                {
                    if (newEdge != smallestEdge)
                    {
                        priorityQueue.Enqueue(newEdge);
                    }
                }
            }
        }
    }
Exemplo n.º 13
0
        public void BinaryHeapSize()
        {
            BinaryHeap<int> h = new BinaryHeap<int>();
            Assert.AreEqual(0, h.Size);

            h.Push(7);
            h.Push(29);
            Assert.AreEqual(2, h.Size);

            h.Pop();
            Assert.AreEqual(1, h.Size);

            h.Pop();
            Assert.AreEqual(0, h.Size);

            h = new BinaryHeap<int>(new[] { 1, 2, 3 });
            Assert.AreEqual(3, h.Size);

            h.Pop();
            Assert.AreEqual(2, h.Size);

            h.Push(12);
            h.Push(21);
            Assert.AreEqual(4, h.Size);
        }
Exemplo n.º 14
0
        public void BinaryHeapTest2()
        {
            BinaryHeap<int> h = new BinaryHeap<int>();

            h.Push(2);
            h.Push(1);
            Assert.AreEqual(1, h.Pop());
            Assert.AreEqual(2, h.Pop());
        }
Exemplo n.º 15
0
        public void BinaryHeapTest1()
        {
            BinaryHeap<int> h = new BinaryHeap<int>(new[] { 4, 7, 1, 6 });
            Assert.AreEqual(h.Pop(), 1);

            h.Push(5);
            Assert.AreEqual(4, h.Pop());
            Assert.AreEqual(5, h.Pop());
        }
 public void BinaryHeapSimpleTest()
 {
     BinaryHeap<int> binaryHeap = new BinaryHeap<int>(10);
     binaryHeap.Insert(4);
     binaryHeap.Insert(6);
     binaryHeap.Insert(3);
     binaryHeap.Insert(8);
     Assert.AreEqual(8, binaryHeap.DeleteMax());
 }
Exemplo n.º 17
0
        public void BinaryHeap_CanRemoveItems()
        {
            var heap = new BinaryHeap<Int32>() { 6, 1, 44, 2, 102, 17, 94, 6 };

            heap.Remove(2);
            heap.Remove(44);

            TheResultingCollection(heap)
                .ShouldBeExactly(1, 6, 6, 17, 94, 102);
        }
Exemplo n.º 18
0
        public static void Main(string[] args)
        {
            BinaryHeap<int> test = new BinaryHeap<int>();
            test.Add(4);
            test.Add(6);
            test.Add(9);
            test.Add(23);

            Console.WriteLine(test.Count);
        }
 public void BinaryHeapDoubleDeleteTest()
 {
     BinaryHeap<int> binaryHeap = new BinaryHeap<int>(10);
     binaryHeap.Insert(4);
     binaryHeap.Insert(1);
     binaryHeap.Insert(3);
     binaryHeap.Insert(8);
     binaryHeap.Insert(0);
     Assert.AreEqual(8, binaryHeap.DeleteMax());
     Assert.AreEqual(4, binaryHeap.DeleteMax());
 }
Exemplo n.º 20
0
        public override void Awake(int maxNumberOfNodes)
        {
            base.Awake(maxNumberOfNodes);
			
            m_openNodes = new BinaryHeap<Node>();
            m_openNodes.Capacity = maxNumberOfNodes;
            m_nodePool = new Pool<Node>(maxNumberOfNodes);
            m_expandedNodes = new Dictionary<int, Pool<Node>.Node>(maxNumberOfNodes);
            m_solution = new LinkedList<Node>();
            m_reachedGoalNodeSuccessCondition = new ReachedGoalNode_SuccessCondition();
        }
Exemplo n.º 21
0
 public void Start()
 {
     if (grid.Source == null || grid.Destination == null)
     {
         return;
     }
     totalVisited = 0;
     IsActive = true;
     openList = new BinaryHeap<double, GridCell>();
     currentCell = grid.Source;
     currentCell.State = GridCellState.Closed;
 }
Exemplo n.º 22
0
        static void Main()
        {
            BinaryHeap<Item> binaryHeap = new BinaryHeap<Item>(3);
            binaryHeap.Insert(new Item(7));
            binaryHeap.Insert(new Item(3));
            binaryHeap.Insert(new Item(9));

            while (binaryHeap.Size > 0)
            {
                Console.WriteLine(binaryHeap.Pop());
            }
        }
        public void Pull_Single_TestCount()
        {
            // Arrange
            var heap = new BinaryHeap <int>();

            // Act
            heap.Insert(3);
            heap.Insert(5);
            heap.Pull();

            // Assert
            Assert.AreEqual(1, heap.Count, "Wrong count");
        }
Exemplo n.º 24
0
    public void Test_InsertItem()
    {
        var heap = new BinaryHeap<int>();
        var minItem = int.MaxValue;

        foreach (var item in items)
        {
            heap.Insert(item);
            minItem = Math.Min(item, minItem);

            Assert.AreEqual(heap.Peek(), minItem);
        }
    }
Exemplo n.º 25
0
        public void Remove_NonExistingElement_False()
        {
            var heap = new BinaryHeap <int>();

            foreach (var item in Enumerable.Range(1, 10))
            {
                heap.Add(item);
            }

            var result = heap.Remove(10000);

            Assert.False(result);
        }
Exemplo n.º 26
0
Arquivo: Maze.cs Projeto: milad-d/pfa
        public Maze(long paramLong, int w, int h)
        {
            java.util.Random localRandom = new java.util.Random(paramLong);

            this.iteration    = 0;
            this.diagonal     = false;
            this.n_directions = 4;

            //this.cde = new Key.Key_comparator();
            //this.u = new TreeSet(this.cde);
            this.u = new BinaryHeap(w * h);

            this.size_x = w;
            this.size_y = h;

            this.cells = new Node[w, h];
            for (int ii = 0; ii < w; ii++)
            {
                for (int jj = 0; jj < h; jj++)
                {
                    this.cells[ii, jj] = new Node(ii, jj);
                }
            }

            int i = (int)(localRandom.nextDouble() * 2147483647.0D) % w;
            int j = (int)(localRandom.nextDouble() * 2147483647.0D) % h;

            this.original_start = (this.robot_cell = this.start = this.cells[i, j]);
            do
            {
                i         = (int)(localRandom.nextDouble() * 2147483647.0D) % w;
                j         = (int)(localRandom.nextDouble() * 2147483647.0D) % h;
                this.goal = this.cells[i, j];
            } while ((this.start.X == this.goal.X) && (this.start.Y == this.goal.Y));

            for (i = 0; i < w; i++)
            {
                for (j = 0; j < h; j++)
                {
                    this.cells[i, j].h         = (Math.Abs(i - this.goal.X) + Math.Abs(j - this.goal.Y));
                    this.cells[i, j].iteration = this.iteration;

                    if ((this.cells[i, j] == this.start) || (this.cells[i, j] == this.goal) ||
                        (localRandom.nextDouble() > 0.25D))
                    {
                        continue;
                    }
                    this.cells[i, j].real_type = 1;
                }
            }
        }
Exemplo n.º 27
0
        public MapPath FindPath(int startX, int startY, int endX, int endY, bool useHeuristic = true)
        {
            if (field == null)
                return null;

             UseHeuristic = useHeuristic;

             List<AStarNode> Closed = new List<AStarNode>();
             BinaryHeap<AStarNode> OpenHeap = new BinaryHeap<AStarNode>(fieldWidth * fieldHeight);
             AStarNode Root;

            Root = new AStarNode();
            Root.parent = null;
            Root.X = startX;
            Root.Y = startY;
            Root.G = 0;
            int offX = Math.Abs(Root.X - endX);
            int offY = Math.Abs(Root.Y - endY);
             if (UseHeuristic == false)
             {
            Root.H = 0;
             }
             else
             {
            if (offX > offY)
               Root.H = 14 * offY + 10 * (offX - offY);
            else
               Root.H = 14 * offX + 10 * (offY - offX);
             }
            OpenHeap.Add(Root.F, Root);

             int res = ProcessLowestNode (endX, endY, Closed, OpenHeap);
            while (res == 0)
            {
                res = ProcessLowestNode(endX, endY, Closed, OpenHeap);
            }

            if (res == -1)
                return null;

             AStarNode node = null;
             if (res == 1)
            node = GetClosedNode(endX, endY, Closed);
             else if (res == 2)
            node = Closed[Closed.Count - 1];

             MapPath result = new MapPath ();
             result.BuildFromFinalAStarNode (node);

             return result;
        }
Exemplo n.º 28
0
        public void AStar()
        {
            //Debug.Log("Start");
            if (start == null || destination == null)
            {
                //Debug.Log("Null");
                return;
            }
            foreach (Node node in AllNodes.NodesGrid)
            {
                if (node != null)
                {
                    node.DistanceToEnemy  = float.MaxValue;
                    node.DistanceToPlayer = float.MaxValue;
                }
            }
            start.DistanceToEnemy  = 0;
            start.DistanceToPlayer = Math.Abs((destination.position - start.position).magnitude);

            int lastIndex             = 1;
            List <IHeapNode> openList = new List <IHeapNode>();

            BinaryHeap.MinPush(openList, start);

            while (lastIndex != 0)
            {
                Node node = (Node)BinaryHeap.MinPop(openList);
                lastIndex--;

                if (node == destination)
                {
                    ReconstructPath();
                    //Debug.Log("Found it");
                    return;
                }
                foreach (Node neighbor in node.Neighbors)
                {
                    float newDistance = node.DistanceToEnemy + Math.Abs((node.position - neighbor.position).magnitude);
                    if (neighbor.DistanceToEnemy <= newDistance)
                    {
                        continue;
                    }
                    neighbor.DistanceToEnemy  = newDistance;
                    neighbor.DistanceToPlayer = newDistance + Math.Abs((destination.position - node.position).magnitude);
                    neighbor.Parent           = node;
                    BinaryHeap.MinPush(openList, neighbor);
                    lastIndex++;
                }
            }
            //Debug.Log("No path");
        }
Exemplo n.º 29
0
        /// <summary>
        /// Search backward from one vertex.
        /// </summary>
        private void SearchBackward(BinaryHeap <EdgePath <T> > queue, EdgePath <T> current)
        {
            if (current != null)
            {
                // check restrictions.
                if (_restrictions != null &&
                    _restrictions.Update(current.Vertex) &&
                    _restrictions.Restricts(current.Vertex))
                { // vertex is restricted, don't settle.
                    return;
                }

                // get the edge enumerator.
                var edgeEnumerator = _graph.GetEdgeEnumerator();

                // add to the settled vertices.
                EdgePath <T> previousLinkedRoute;
                if (_backwardVisits.TryGetValue(current.Vertex, out previousLinkedRoute))
                {
                    if (_weightHandler.IsLargerThan(previousLinkedRoute.Weight, current.Weight))
                    { // settle the vertex again if it has a better weight.
                        _backwardVisits[current.Vertex] = current;
                    }
                }
                else
                { // settled the vertex.
                    _backwardVisits.Add(current.Vertex, current);
                }

                // get neighbours.
                edgeEnumerator.MoveTo(current.Vertex);

                // add the neighbours to the queue.
                while (edgeEnumerator.MoveNext())
                {
                    bool?neighbourDirection;
                    var  neighbourWeight = _weightHandler.GetEdgeWeight(edgeEnumerator.Current, out neighbourDirection);

                    if (neighbourDirection == null || !neighbourDirection.Value)
                    { // the edge is backward, and is to higher or was not contracted at all.
                        var neighbourNeighbour = edgeEnumerator.Neighbour;
                        if (!_backwardVisits.ContainsKey(neighbourNeighbour))
                        { // if not yet settled.
                            var routeToNeighbour = new EdgePath <T>(
                                neighbourNeighbour, _weightHandler.Add(current.Weight, neighbourWeight), current);
                            queue.Push(routeToNeighbour, _weightHandler.GetMetric(routeToNeighbour.Weight));
                        }
                    }
                }
            }
        }
Exemplo n.º 30
0
        public void ExtactMaxExtreme()
        {
            const int count = 1048576;
            var       heap  = new BinaryHeap(count);

            for (int i = 0; i < count; i++)
            {
                heap.AddElement(i);
            }
            for (int i = count - 1; i >= 0; i--)
            {
                Assert.AreEqual(i, heap.ExtractMax());
            }
        }
Exemplo n.º 31
0
        public void EmptyHeapComplex()
        {
            var heap = new BinaryHeap(1024);

            for (int i = 1; i <= 1000; i++)
            {
                heap.AddElement(i);
            }
            for (int i = 1000; i >= 1; i--)
            {
                heap.ExtractMax();
            }
            Assert.IsTrue(heap.Empty);
        }
Exemplo n.º 32
0
        protected override void OnSort <T>(ref T[] array, int arrayLength)
        {
            BinaryHeap <T> binaryHeap = new BinaryHeap <T>(HeapMode.MinHeap, arrayLength);

            for (int i = 0; i < arrayLength; i++)
            {
                binaryHeap.Add(array[i]);
            }

            for (int i = 0; i < arrayLength; i++)
            {
                array[i] = binaryHeap.ExtractTop();
            }
        }
Exemplo n.º 33
0
        public static void Constructor_UseCustomComparer_BuildCorrectHeap()
        {
            var revHeap = new BinaryHeap <int>(Comparer <int> .Create((x, y) => y.CompareTo(x)));

            foreach (var i in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
            {
                revHeap.Push(i);
            }

            Assert.AreEqual(10, revHeap.Count);
            Assert.AreEqual(1, revHeap.Peek());
            Assert.AreEqual(1, revHeap.Pop());
            Assert.AreEqual(2, revHeap.Peek());
        }
Exemplo n.º 34
0
        private IEnumerable <T> HeapSort <T>(IEnumerable <T> items)
        {
            var heap = new BinaryHeap <T, T>();

            foreach (var item in items)
            {
                heap.Add(item, item);
            }

            while (heap.Count != 0)
            {
                yield return(heap.ExtractFirst());
            }
        }
        public void BinaryHeapPushRangePopSimple()
        {
            var heap   = new BinaryHeap <int>(Comparer <int> .Default);
            var values = new List <int> {
                1, -5, 6, 7, -6, 11, -22, 6345, -3423, 34, 23412, 12, 12, 543, 12, 1, -22
            };

            heap.PushRange(values);
            values.Sort();
            foreach (var value in values)
            {
                Assert.AreEqual(value, heap.Pop());
            }
        }
Exemplo n.º 36
0
        private double GetMedian(BinaryHeap <double> minHeap, BinaryHeap <double> maxHeap)
        {
            var smallerHeap = minHeap.Size() > maxHeap.Size() ? maxHeap : minHeap;
            var biggerHeap  = minHeap.Size() > maxHeap.Size() ? minHeap : maxHeap;

            if (smallerHeap.Size() == biggerHeap.Size())
            {
                return((smallerHeap.Peek() + biggerHeap.Peek()) / 2);
            }
            else
            {
                return(biggerHeap.Peek());
            }
        }
        public void InsertAndMinimum5()
        {
            BinaryHeap <int, int> binaryHeap = BinaryHeapFactory.Create(2);
            var keyValuePairs = new KeyValuePair <int, int> [2];
            var s0            = new KeyValuePair <int, int>(16384, 16384);

            keyValuePairs[1] = s0;

            CheckInsertAndMinimumHeap(
                binaryHeap,
                keyValuePairs,
                2,
                2);
        }
Exemplo n.º 38
0
        public void CheckAllCases_Of_InvalidOperationException()
        {
            var heap = new BinaryHeap <string, int>();

            Assert.IsTrue(heap.IsEmpty);
            Assert.IsFalse(heap.TryPop(out _));
            Assert.Throws <InvalidOperationException>(() => heap.Pop());
            Assert.IsFalse(heap.TryPeek(out _));
            Assert.Throws <InvalidOperationException>(() => heap.Peek());
            Assert.IsFalse(heap.TryUpdate("A", 0));
            Assert.Throws <InvalidOperationException>(() => heap.Update("A", 0));
            Assert.IsFalse(heap.TryReplace("A", 0, out _));
            Assert.Throws <InvalidOperationException>(() => heap.Replace("A", 0));
        }
Exemplo n.º 39
0
    public void testOneElement()
    {
        int        row = 1;
        int        col = 1;
        BinaryHeap bh  = new BinaryHeap();

        bh.CreateHeap(row, col);
        Node one = createNode();

        bh.InsertHeap(one, Mathf.Infinity);
        Assert.IsTrue(bh.CheckMin() == one);
        Assert.IsTrue(bh.CheckMin() == one);
        Assert.IsTrue(bh.ExtractMinKey() == one);
    }
Exemplo n.º 40
0
        public void BinaryHeapEmptyPeekTest()
        {
            BinaryHeap binaryHeap = new BinaryHeap();

            try
            {
                binaryHeap.Peek();
            }
            catch (BinaryHeapException)
            {
                return;
            }
            Assert.Fail();
        }
Exemplo n.º 41
0
        public void BinaryHeapPopTest()
        {
            int[]      array      = new int[] { 11, 5, 33, 65, 10, 653, 14, 3, 16, 5, 4 };
            BinaryHeap binaryHeap = new BinaryHeap(array);

            if (binaryHeap.Pop() != 3)
            {
                Assert.Fail();
            }
            if (binaryHeap.Pop() != 4)
            {
                Assert.Fail();
            }
        }
Exemplo n.º 42
0
        public static void BinaryHeap()   // Binary Heap (ints), de root is altijd de laagste waarde.
        {
            BinaryHeap heap = new BinaryHeap();

            heap.add(1);
            heap.add(2);
            heap.add(3);
            heap.add(4);
            heap.add(5);
            heap.add(6);
            heap.add(2);
            Console.WriteLine(heap.FindMin());
            heap.printPreOrder();
        }
Exemplo n.º 43
0
    // This uses Dijkstra's algorithm: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm.
    // We return immediately upon visiting the destination city, and we don't initialize the
    // heap with all cities. We only add cities to the heap when reaching one of their neighbor
    // cities. Without a pre-filled heap to rely on, we track what cities have been visited
    // using an array of bools.
    public static int Solve(List <KeyValuePair <int, int> >[] cityGraph, int sourceCity, int destinationCity)
    {
        var pathCosts = new BinaryHeap(sourceCity);

        bool[] visitedCities = new bool[cityGraph.Length];

        while (!pathCosts.IsEmpty)
        {
            var cheapestPath   = pathCosts.Extract();
            int city           = cheapestPath.Key;
            int pathCostToCity = cheapestPath.Value;

            if (city == destinationCity)
            {
                return(pathCostToCity);
            }

            var neighboringEdges = cityGraph[city];
            for (int e = 0; e < neighboringEdges.Count; ++e)
            {
                int neighbor = neighboringEdges[e].Key;
                if (visitedCities[neighbor])
                {
                    continue;
                }

                int pathCostToNeighborThroughCity = pathCostToCity + neighboringEdges[e].Value;
                int currentPathCostToNeighbor;

                // We know the neighboring city hasn't been visited yet, so we need to maintain its
                // path cost in the heap. If it's already in the heap, see if a cheaper path exists
                // to it through the city we're visiting. If it isn't in the heap yet, add it.
                if (pathCosts.TryGetValue(neighbor, out currentPathCostToNeighbor))
                {
                    if (pathCostToNeighborThroughCity < currentPathCostToNeighbor)
                    {
                        pathCosts.Update(neighbor, pathCostToNeighborThroughCity);
                    }
                }
                else
                {
                    pathCosts.Add(neighbor, pathCostToNeighborThroughCity);
                }
            }

            visitedCities[city] = true;
        }

        throw new NotSupportedException();
    }
        public void BinaryHeapRemoveAll()
        {
            var heap = new BinaryHeap <float>(NumericUtilities.FloatNumberComparer <float>())
            {
                0.1f, 0.56f, 0.234f, 0.66f, 0.231f, 0.234f, 0.1f
            };

            heap.RemoveAll(0.1f);
            Assert.IsTrue(heap.Comparer.Compare(0.231f, heap.Pop()) == 0);
            heap.RemoveAll(v => heap.Comparer.Compare(0.234f, v) == 0);
            Assert.IsTrue(heap.Comparer.Compare(0.56f, heap.Pop()) == 0);
            Assert.IsTrue(heap.Comparer.Compare(0.66f, heap.Pop()) == 0);
            Assert.AreEqual(heap.Count, 0);
        }
        private static void InsertAndEnumerate <TPriority, TValue>(
            [NotNull] BinaryHeap <TPriority, TValue> heap,
            [NotNull] KeyValuePair <TPriority, TValue>[] pairs)
        {
            var dictionary = new Dictionary <TPriority, TValue>();

            foreach (KeyValuePair <TPriority, TValue> pair in pairs)
            {
                heap.Add(pair.Key, pair.Value);
                dictionary[pair.Key] = pair.Value;
            }

            QuikGraphAssert.TrueForAll(heap, pair => dictionary.ContainsKey(pair.Key));
        }
        public void InsertAndMinimum4()
        {
            BinaryHeap <int, int> binaryHeap = BinaryHeapFactory.Create(3);
            var keyValuePairs = new KeyValuePair <int, int> [2];
            var s0            = new KeyValuePair <int, int>(int.MinValue, default);

            keyValuePairs[1] = s0;

            CheckInsertAndMinimumHeap(
                binaryHeap,
                keyValuePairs,
                3,
                2);
        }
Exemplo n.º 47
0
        public void Remove_MinHeap_HeapifyUp()
        {
            var heap = new BinaryHeap <int>(8)
            {
                1, 2, 30, 17, 19, 36, 37, 25
            };

            var result = heap.Remove(37);

            Assert.True(result);
            Assert.True(heap.Validate());
            Assert.Equal(25, heap[2]);
            Assert.Equal(30, heap[6]);
        }
Exemplo n.º 48
0
        public void ReHeapifyMinTest()
        {
            a = Helpers.BuildRandomArray(30);
            h = BinaryHeap <int> .MaxHeapify(a);

            Assert.IsTrue(h.IsMaxHeap);
            Assert.AreEqual(30, h.HeapSize);

            a = Helpers.BuildRandomArray(20);
            h.ReHeapifyMin(a);

            Assert.IsTrue(h.IsMinHeap);
            Assert.AreEqual(20, h.HeapSize);
        }
Exemplo n.º 49
0
        public void Pull_EmptyHeap()
        {
            // Arrange
            var heap = new BinaryHeap <int>();

            // Act
            // heap.Pull();

            // instead of [ExpectedException(typeof(InvalidOperationException))]
            var ex = Assert.Throws <InvalidOperationException>(() => heap.Pull());

            // test the message itself
            // Assert.That(ex.Message == "");
        }
Exemplo n.º 50
0
        public void insertIntoFullHeapTest()
        {
            BinaryHeap binaryHeap = new BinaryHeap(new int[] { 1, 2, 3 });

            try
            {
                binaryHeap.insert(4);
            }
            catch (BinaryHeapException)
            {
                return;
            }
            Assert.Fail();
        }
Exemplo n.º 51
0
        public void removeAtTest()
        {
            BinaryHeap <int, int> target = new BinaryHeap <int, int>();

            target.Add(1, 3);
            target.Add(1, 2);
            Assert.IsTrue(target.IndexOf(2) == 0);

            target.Add(0, 1);

            Assert.IsTrue(target.Minimum().Key == 0);
            Assert.IsTrue(target.RemoveAt(2).Value == 2);
            Assert.IsTrue(target.RemoveAt(0).Value == 1);
        }
Exemplo n.º 52
0
        private static void Insert <TPriority, TValue>(
            [NotNull] BinaryHeap <TPriority, TValue> heap,
            [NotNull] KeyValuePair <TPriority, TValue>[] pairs)
        {
            int count = heap.Count;

            foreach (KeyValuePair <TPriority, TValue> pair in pairs)
            {
                heap.Add(pair.Key, pair.Value);
                AssertInvariant(heap);
            }

            Assert.AreEqual(heap.Count, count + pairs.Length);
        }
Exemplo n.º 53
0
    static void Main()
    {
        BinaryHeap binaryHeap = new BinaryHeap();

        binaryHeap.add(2);
        binaryHeap.add(16);
        binaryHeap.add(12);
        binaryHeap.add(7);
        binaryHeap.add(5);
        binaryHeap.add(12);
        binaryHeap.add(1);

        binaryHeap.testInvariants();

        System.Console.WriteLine("Binary Max Heap with values added 2, 16, 12, 7, 5, 12, 1 using add() function");
        binaryHeap.printList();
        System.Console.WriteLine();

        System.Console.WriteLine("Binary Heap popTop assert test");
        //loop pops until heap is empty and asserts each value popped is larger than previous popped value
        //also asserts invariants are kept through each iteration
        for (int previousPop = binaryHeap.popTop(); binaryHeap.heapList.Count != 1;)
        {
            binaryHeap.printList();
            System.Console.WriteLine();
            int currentPop = binaryHeap.popTop();
            Debug.Assert(previousPop >= currentPop);
            binaryHeap.testInvariants();
            previousPop = currentPop;
        }

        List <int> myList = new List <int>(new int[] { 0, 5, 2, 1, 21, 12, 2, 4, 8 });

        binaryHeap.buildHeap(myList);

        binaryHeap.testInvariants();

        System.Console.WriteLine("Binary Max Heap with values 5, 2, 1, 21, 12, 2, 4 added using buildHeap() function");
        binaryHeap.printList();
        System.Console.WriteLine();

        System.Console.WriteLine("Heap Sort");
        binaryHeap.heapSort();
        binaryHeap.printList();

        for (int i = 0; i < binaryHeap.heapList.Count - 2; i++)
        {
            Debug.Assert(binaryHeap[i] <= binaryHeap[i + 1]);
        }
    }
Exemplo n.º 54
0
        public void AscendingSequenceTest()
        {
            var bh    = new BinaryHeap <int>();
            var count = 1024;

            for (var i = 0; i <= count; i++)
            {
                bh.Push(i);
            }
            for (var i = count; 0 <= i; i--)
            {
                Assert.Equal(i, bh.Pop());
            }
        }
Exemplo n.º 55
0
        public void TestAdd()
        {
            BinaryHeap<int> heap = new BinaryHeap<int>();

            Assert.AreEqual(0, heap.Count);

            heap.Add(1);
            Assert.AreEqual(1, heap.Count);

            heap.Add(1);
            Assert.AreEqual(2, heap.Count);

            heap.Add(2);
            Assert.AreEqual(3, heap.Count);
        }
Exemplo n.º 56
0
    public void Test_RemoveRoot()
    {
        var heap = new BinaryHeap<int>();
        foreach (var item in items)
        {
            heap.Insert(item);
        }

        var sortedItems = new List<int>(items);
        sortedItems.Sort();
        foreach (var item in sortedItems)
        {
            Assert.AreEqual(heap.RemoveRoot(), item);
        }
    }
Exemplo n.º 57
0
        public void BinaryHeap_CanAddItems()
        {
            var heap = new BinaryHeap<Int32>();

            heap.Add(6);
            heap.Add(1);
            heap.Add(44);
            heap.Add(2);
            heap.Add(102);
            heap.Add(17);
            heap.Add(94);
            heap.Add(6);

            TheResultingCollection(heap)
                .ShouldBeExactly(1, 2, 6, 6, 17, 44, 94, 102);
        }
Exemplo n.º 58
0
        /// <summary>
        /// Creates a new pre-processor.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="calculator"></param>
        /// <param name="witnessCalculator"></param>
        public CHPreprocessor(GraphBase<CHEdgeData> target,
                INodeWeightCalculator calculator,
                INodeWitnessCalculator witnessCalculator)
        {
            _target = target;

            _calculator = calculator;
            _witnessCalculator = witnessCalculator;

            _queue = new BinaryHeap<uint>(target.VertexCount + (uint)System.Math.Max(target.VertexCount * 0.1, 5));
            _lowestPriorities = new float[target.VertexCount + (uint)System.Math.Max(target.VertexCount * 0.1, 5)];
            for (int idx = 0; idx < _lowestPriorities.Length; idx++)
            { // uncontracted = priority != float.MinValue.
                _lowestPriorities[idx] = float.MaxValue;
            }
        }
Exemplo n.º 59
0
        public void TestBinaryHeap1()
        {
            var heap = new BinaryHeap<double>(10);
            heap.Push (5);
            Assert.True (heap.Peek () == 5);

            heap.Push (4);
            Assert.True(heap.Pop() == 4);
            Assert.True(heap.Pop() == 5);

            heap.Push (12);
            heap.Push (20);
            heap.Push (30);
            heap.Push (50);
            heap.Push (2);
            Assert.True(heap.Pop() == 2);
        }
Exemplo n.º 60
0
        public void Add_AddingNewElement_ElementAddedToHeap()
        {
            // arrange
            int[] array = {1, 3, 4, 5};
            int newElement = 2;
            var heap = new BinaryHeap<int>();
            heap.BuildHeap(array);
            Type heapType = typeof(BinaryHeap<int>);
            FieldInfo field = heapType.GetField( "list", BindingFlags.NonPublic | BindingFlags.Instance);
            var list = (List<int>)field.GetValue(heap);

            // act
            heap.Add(newElement);

            // assert
            Assert.IsTrue(list.Contains(2));
        }