Exemplo n.º 1
0
        private void BuildHeapTree(Node <T, G>[] myInput)
        {
            Tree = new HeapTree <T, G>(myInput.Length);

            for (int i = 0; i < myInput.Length; i++)
            {
                Tree.Insert(myInput[i].Key, myInput[i].Value);
            }
        }
Exemplo n.º 2
0
        public void Insert()
        {
            var heapTree = new HeapTree();

            heapTree.Insert(55);
            int index = heapTree.Search(55);

            Assert.AreEqual(1, index);
        }
Exemplo n.º 3
0
        public void Empty()
        {
            HeapTree <int> tree = new HeapTree <int>(5);

            Assert.True(tree.IsEmpty());

            tree.Insert(5);

            Assert.False(tree.IsEmpty());
        }
Exemplo n.º 4
0
        public void Insert()
        {
            HeapTree <int> tree = new HeapTree <int>(10);

            int[] expected = { 1, 3, 2, 6, 4, 5, 0, 0, 0, 0 };

            for (int i = 6; i > 0; i--)
            {
                tree.Insert(i);
            }

            Assert.Equal(expected, tree.GetTree());
        }
Exemplo n.º 5
0
        public void HeapTree_Deserialize_SmallTest()
        {
            var tree = new HeapTree();

            var list = new List <int>()
            {
                2, 3, 1
            };
            var result = tree.CreateTree(list).Result;

            Assert.AreEqual(3, result.Data);
            Assert.AreEqual(2, result.LeftNode.Data);
            Assert.AreEqual(1, result.RightNode.Data);
        }
Exemplo n.º 6
0
        public void HeapTree_Search()
        {
            var heapTree = new HeapTree();

            var list = new List <int>()
            {
                2, 4, 6
            };
            var tree = heapTree.CreateTree(list).Result;

            var item = heapTree.Search(tree, 2).Result;

            Assert.AreEqual(2, item.Data);
        }
Exemplo n.º 7
0
        public void DeleteNode(T data)
        {
            var deleteNode = HeapTree.Where(o => o.CompareTo(data) == 0).FirstOrDefault();

            if (deleteNode == null)
            {
                throw new ArgumentException("delete data doesn't exist in heap");
            }
            var lastNode        = HeapTree[LastIndex];
            var deleteNodeIndex = Array.IndexOf(HeapTree, deleteNode);

            HeapTree[deleteNodeIndex] = lastNode;
            ReHeapifyFromIndex(deleteNodeIndex);
            LastIndex--;
        }
Exemplo n.º 8
0
        public void HeapTree_Deserialize()
        {
            var tree = new HeapTree();

            var list = new List <int>()
            {
                3, 6, 2, 4, 5, 1
            };
            var result = tree.CreateTree(list).Result;

            Assert.AreEqual(6, result.Data);
            Assert.AreEqual(5, result.LeftNode.Data);
            Assert.AreEqual(4, result.LeftNode.LeftNode.Data);
            Assert.AreEqual(3, result.LeftNode.RightNode.Data);
            Assert.AreEqual(2, result.RightNode.Data);
            Assert.AreEqual(1, result.RightNode.LeftNode.Data);
        }
Exemplo n.º 9
0
        public void Pop()
        {
            HeapTree <int> tree = new HeapTree <int>(10);

            int[] expected = { 2, 3, 5, 6, 4, 0, 0, 0, 0, 0 };

            for (int i = 6; i > 0; i--)
            {
                tree.Insert(i);
            }

            int temp = tree.Pop();

            Assert.Equal(1, temp);

            Assert.Equal(expected, tree.GetTree());
        }
    public PathFinder(GridModel model)
    {
        mModel = model;
        mGridX = (ushort)mModel.row;
        mGridY = (ushort)mModel.column;

        mGridXBitWide = (ushort)(Math.Log(mGridX - 1, 2) + 1);
        mGridXMinus = (ushort)( Math.Pow(2, mGridXBitWide) - 1);

        int maxIndex = ( (mGridY - 1) << mGridXBitWide ) + (mGridX - 1);
        //0 - maxIndex
        int size = maxIndex + 1;
        if (null == mCalcGrid || mCalcGrid.Length != (size))
            mCalcGrid = new PathNodeFast[size];

        mOpen = new HeapTree(mCalcGrid);
    }
Exemplo n.º 11
0
        public void HeapTree_Insert_AtMiddle()
        {
            var heapTree = new HeapTree();

            var list = new List <int>()
            {
                2, 4, 6
            };
            var tree = heapTree.CreateTree(list).Result;

            Assert.AreEqual(6, tree.Data);
            Assert.AreEqual(4, tree.LeftNode.Data);
            Assert.AreEqual(2, tree.RightNode.Data);

            tree = heapTree.Insert(tree, 5).Result;
            Assert.AreEqual(6, tree.Data);
            Assert.AreEqual(5, tree.LeftNode.Data);
            Assert.AreEqual(4, tree.LeftNode.LeftNode.Data);
            Assert.AreEqual(2, tree.RightNode.Data);
        }
Exemplo n.º 12
0
    public PathFinder(GridModel model)
    {
        mModel = model;
        mGridX = (ushort)mModel.row;
        mGridY = (ushort)mModel.column;

        mGridXBitWide = (ushort)(Math.Log(mGridX - 1, 2) + 1);
        mGridXMinus   = (ushort)(Math.Pow(2, mGridXBitWide) - 1);

        int maxIndex = ((mGridY - 1) << mGridXBitWide) + (mGridX - 1);
        //0 - maxIndex
        int size = maxIndex + 1;

        if (null == mCalcGrid || mCalcGrid.Length != (size))
        {
            mCalcGrid = new PathNodeFast[size];
        }

        mOpen = new HeapTree(mCalcGrid);
    }
Exemplo n.º 13
0
        public void Delete()
        {
            var heapTree = new HeapTree();

            heapTree.Insert(5);
            heapTree.Insert(6);
            heapTree.Insert(15);
            heapTree.Insert(7);
            heapTree.Insert(12);
            heapTree.Insert(9);
            heapTree.Insert(2);
            heapTree.Insert(54);
            heapTree.Insert(59);
            heapTree.Display();
            heapTree.DeleteRoot();
            heapTree.Display();
            int index = heapTree.Search(54);

            Assert.AreEqual(1, index);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sorts array
        /// </summary>
        /// <param name="arr">The array to be sorted</param>
        /// <returns>The sorted array</returns>
        public T[] Sort(T[] arr)
        {
            // Sort is done by continuing to pop value into new array
            HeapTree <T> tree = new HeapTree <T>(arr.Length);

            T[] ret = new T[arr.Length];
            int ap  = 0;

            // I need to insert into tree
            for (int i = 0; i < arr.Length; i++)
            {
                tree.Insert(arr[i]);
            }

            while (!tree.IsEmpty())
            {
                ret[ap] = tree.Pop();
                ap++;
            }

            return(ret);
        }
Exemplo n.º 15
0
        private static void TestHeapTree(int[] myArray)
        {
            Console.WriteLine("\n======== H-E-A-P-T-R-E-E ==================" +
                              "\n======== Complexity: Time O(n) Espace O(1)\nSteps:\n");

            StringBuilder result = new StringBuilder("Inserting keys ");

            HeapTree <int, int> tree = new HeapTree <int, int>(myArray.Length);
            Random rnd = new Random();

            for (int i = 0; i < myArray.Length; i++)
            {
                tree.Insert(myArray[i], rnd.Next(1, myArray.Length * 100));
                result.Append(myArray[i] + " ");
                Console.WriteLine("Insert time: " + tree.HeapLog.ToString());
            }

            result.Append("\nMy heap result: ");
            for (int i = 0; i < myArray.Length; i++)
            {
                result.Append(tree.Heap[i].Key + " ");
            }

            Console.WriteLine("\n" + result);

            Console.WriteLine("\nIn Order:\n" + tree.InOrder());
            Console.WriteLine("\nPos Order:\n" + tree.PosOrder());
            Console.WriteLine("\nPre Order:\n" + tree.PreOrder());

            result.Clear();
            for (int i = 0; i < myArray.Length; i++)
            {
                result.Append(tree.Remove().Key + " ");
            }
            Console.WriteLine("\nRemoved nodes:" + result + "\n");
        }
Exemplo n.º 16
0
    public void FindPath(PathRequestData requestData, Action <PathResultData> callbackAction)
    {
        Stopwatch sw = new Stopwatch(); /* Used in order to see the performance of the path-finding system before/after heap tree optimization.
                                         *           Stopwatch creates some kind of overhead so disable it in the final build.*/

        sw.Start();
        // CallbackPathResult elements
        Vector2[] pathWayPoints = new Vector2[0];
        bool      pathSuccess   = false;

        #region A* Algorithm
        // Find the start and end nodes on the current grid system
        Node startNode  = _gridSystem.NodeFromWorldPoint(requestData.PathStart);
        Node targetNode = _gridSystem.NodeFromWorldPoint(requestData.PathEnd);
        // Only do calculations if nodes are walkable
        if (/*startNode.Walkable &&*/ targetNode.Walkable)
        {
            HeapTree <Node> openNodeSet   = new HeapTree <Node>(_gridSystem.MaxHeapSize); // Binary Heap Tree for A* iteration - optimization
            HashSet <Node>  closedNodeSet = new HashSet <Node>();                         // Hash Set for the closed node set of the A* algorithm
            //
            openNodeSet.AddItem(startNode);                                               // Begin with the starting node
            while (openNodeSet.HeapTreeSize > 0)                                          // While the open node set is not empty
            {
                Node currentNode = openNodeSet.RemoveFirst();                             // First in heap tree is the one with the lowest score.
                closedNodeSet.Add(currentNode);                                           // Transfer this node from open set to closed set
                if (currentNode == targetNode)                                            // PathResult status check - if the target node is reached
                {
                    sw.Stop();
                    print("Path found in : " + sw.ElapsedMilliseconds + " mili-seconds ");
                    pathSuccess = true;

                    break; // PathResult has been found. Exit the while loop
                }          // If not found start neighbor cost calculations

                // List of the adjacent neighboring nodes. They are pre-calculated and stored in Nodes - optimization (Heap -> Stack Memory Allocation)
                List <Node> neighborNodeSet = currentNode.NeighborNodes;  // Get the pre-computed neighbor nodes
                for (int i = 0; i < neighborNodeSet.Count; i++)
                {
                    if (!neighborNodeSet[i].Walkable || closedNodeSet.Contains(neighborNodeSet[i]))
                    {
                        continue; // Non-walkable nodes and already closed nodes are passed
                    }
                    // New movement G cost with the path through current node
                    int movementCostToNeighbor = currentNode.GCost + GetDistance(currentNode, neighborNodeSet[i]);
                    // If the new distance from starting node is shorter and open node set does not contain this neighbor
                    if (movementCostToNeighbor < neighborNodeSet[i].GCost || !openNodeSet.ContainsItem(neighborNodeSet[i]))
                    {
                        neighborNodeSet[i].GCost      = movementCostToNeighbor; // Update the distance from starting node with its new path
                        neighborNodeSet[i].HCost      = GetDistance(neighborNodeSet[i], targetNode);
                        neighborNodeSet[i].ParentNode = currentNode;            // Set the new parent of the node for final path detection
                        if (!openNodeSet.ContainsItem(neighborNodeSet[i]))      // If it is not in the open set, add it to the set
                        {
                            openNodeSet.AddItem(neighborNodeSet[i]);
                        }
                        else
                        {
                            openNodeSet.UpdateItem(neighborNodeSet[i]); // If already in the set then the values are changed
                        }
                    }
                }
            }
        }
        #endregion

        // If an available path is found
        if (pathSuccess)
        {
            pathWayPoints = ReTracePath(startNode, targetNode);     // Find the path way-points by re-tracing parent nodes
            pathSuccess   = pathWayPoints.Length > 0;               // Set path to success if there is at least one way-point
        }

        // Trigger the callback, path is found. This will trigger the queue in the path-finding request manager
        callbackAction(new PathResultData(pathWayPoints, _wayPointNodesCache, pathSuccess, requestData.CallbackPathRequest));
    }
Exemplo n.º 17
0
 public PriorityQueue(int maxSize)
 {
     tree = new HeapTree <T>(maxSize);
 }