public void dijkstra(int source)
    {
        for (int i = 1; i <= nodes; i++)
        {
            dis[i] = int.MaxValue;
        }

        PriorityQueue <int> pq = new PriorityQueue <int>();

        pq.Add(source, 0);
        dis[source] = 0;

        while (pq.Count() > 0)
        {
            int u = pq.RemoveMin();

            for (int j = 0; j < graph[u].Count; j++)
            {
                int v = graph[u][j].v;
                int w = graph[u][j].w;

                if (dis[u] + w < dis[v])
                {
                    dis[v] = dis[u] + w;
                    pq.Add(v, dis[v]);
                }
            }
        }
    }
Exemple #2
0
    /// <summary>
    /// A* pathfinding from a source point to a destination point.
    /// Requires a Grid class that has public methods
    /// GetMovementCost(Point p), IsEmpty(Point p), and Neighbors(Point p)
    /// </summary>
    /// <param name="grid">The grid object that contains tile data</param>
    /// <param name="src">Source, the starting point</param>
    /// <param name="dest">Destination, the ending point</param>
    /// <returns>A list of points in the path, null if no path</returns>
    public static List <Point> FindPath(Grid grid, Point src, Point dest)
    {
        if (!grid.IsEmpty(dest))
        {
            return(null);
        }

        PriorityQueue <PathPoint> pq = new PriorityQueue <PathPoint>(false);

        pq.Add(new PathPoint(src, 0, null), 0);
        HashSet <PathPoint> visited = new HashSet <PathPoint>();

        PathPoint current = null;

        while (pq.Count > 0)
        {
            current = pq.Remove();
            if (current.point == dest)
            {
                return(BuildPath(current));
            }

            foreach (Point n in grid.Neighbors(current.point))
            {
                int       distance = current.distance + grid.GetMovementCost(n);
                PathPoint p        = new PathPoint(n, distance, current);
                if (grid.IsEmpty(n) && visited.Add(p))
                {
                    pq.Add(p, p.distance + Heuristic(n, dest));
                }
            }
        }

        return(null);
    }
Exemple #3
0
        public void MinHeapClassRemovalTest()
        {
            var heap = new PriorityQueue <TestNode>(HeapType.Min, Allocator.Persistent);

            heap.Add(new TestNode {
                Value = 8
            });
            heap.Add(new TestNode {
                Value = 2
            });
            heap.Add(new TestNode {
                Value = 5
            });
            heap.Add(new TestNode {
                Value = 10
            });
            heap.Add(new TestNode {
                Value = 3
            });

            heap.Remove();
            heap.Remove();

            Assert.AreEqual(5, heap.Peek().Value);

            heap.Dispose();
        }
Exemple #4
0
    /// <summary>
    /// Функция поиска ближайшей к финишу точки
    /// </summary>
    /// <param name="position">координаты финиша</param>
    /// <param name="outpos">выходные координаты</param>
    /// <param name="_maxHeight">максимальная высота</param>
    /// <returns>true - найдено, false - не найдено</returns>
    public static bool FindFreeCell(Vector2Int position, out Vector2Int outpos, float _maxHeight = 0)
    {
        PriorityQueue <NavGridPoint> queue = new PriorityQueue <NavGridPoint>();
        NavGridPoint temp = new NavGridPoint(position, 0);

        queue.Add(temp);
        while (queue.Peek().order < GameConstants.FreeCellMaxOrder)
        {
            temp = queue.GetMin();
            if (!TerrainNavGrid.Instance.IsCellUsed(temp.Position))
            {
                outpos = temp.Position;
                return(true);
            }
            foreach (Vector2Int v in MoveArray)
            {
                NavGridPoint add = new NavGridPoint(temp.Position + v, temp.order + 1);
                if (!IsPointInField(add.Position) ||
                    (_maxHeight != 0 && TerrainHeightMap.Instance.GetHeight(temp.Position) -
                     TerrainHeightMap.Instance.GetHeight(add.Position) >= _maxHeight))
                {
                    continue;
                }
                add.distance = GetDistance(position, add.Position);
                queue.Add(add);
            }
        }
        outpos = position;
        return(false);
    }
Exemple #5
0
        public int KthSmallest(int[][] matrix, int k)
        {
            // Assume matrix[i][j] is the (m)th smallest element, matrix[i + 1][j] and matrix[i][j + 1] should be
            // candidates for the (m + 1)th smallest element. So we start from matrix[0][0] and add all the candidates
            // for [1 to k]th smallest element to a priority queue.
            var minPQ = new PriorityQueue <Point>(Comparer <Point> .Create((x, y) => matrix[y.i][y.j] - matrix[x.i][x.j]));

            minPQ.Add(new Point(0, 0));
            while (--k > 0)
            {
                var min = minPQ.DeleteTop();
                // We should somehow avoid visiting an element twice. So we only "move right" when in 0th row.
                // If we come to an element that is not in 0th row, for example matrix[1][0], we don't need to
                // move right to add matrix[1][1] because matrix[0][1] is or was in the priority queue, and because
                // matrix[0][1] is smaller than [1][1], matrix[1][1] either was added or will be added from matrix[0][1].
                if (min.i == 0 && min.j + 1 < matrix.Length)
                {
                    minPQ.Add(new Point(min.i, min.j + 1));
                }
                if (min.i + 1 < matrix.Length)
                {
                    minPQ.Add(new Point(min.i + 1, min.j));
                }
            }
            return(matrix[minPQ.PeekTop().i][minPQ.PeekTop().j]);
        }
Exemple #6
0
        private IBinaryTree <char> BinaryTreeCreation(Dictionary <char, int> frequencyDict)
        {
            if (frequencyDict.Count == 1)
            {
                var tree = new BinaryTree <char>(frequencyDict.Keys.FirstOrDefault());
                tree.Merge(new BinaryTree <char>());
                return(tree);
            }
            var priorityQueue = new PriorityQueue <IBinaryTree <char> >();

            foreach (var(symbol, frequency) in frequencyDict)
            {
                var tree = new BinaryTree <char>(symbol);
                priorityQueue.Add(tree, frequency);
            }
            while (priorityQueue.Count > 1)
            {
                var(tree, frequency)           = priorityQueue.ExtractMin();
                var(otherTree, otherFrequency) = priorityQueue.ExtractMin();
                tree.Merge(otherTree);
                priorityQueue.Add(tree, frequency + otherFrequency);
            }
            return(priorityQueue.Count > 0
                       ? priorityQueue.ExtractMin().Item1
                       : null);
        }
Exemple #7
0
        public void Simple()
        {
            var priorityQueue = new PriorityQueue <string, int>(PriorityQueueType.Maximum)
            {
                "5"
            };

            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Contains("5"));
            Assert.IsTrue(priorityQueue.Remove("5"));
            Assert.AreEqual(priorityQueue.Count, 0);

            priorityQueue.Add("6");
            priorityQueue.Add("7");
            priorityQueue.Add("2", 4);

            Assert.AreEqual(priorityQueue.Count, 3);
            Assert.IsTrue(priorityQueue.Contains("6"));
            Assert.IsTrue(priorityQueue.Contains("7"));
            Assert.IsTrue(priorityQueue.Contains("2"));

            Assert.IsFalse(priorityQueue.Remove("8"));

            Assert.IsTrue(priorityQueue.Remove("7"));
            Assert.AreEqual(priorityQueue.Count, 2);
            Assert.IsTrue(priorityQueue.Remove("2"));
            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Remove("6"));
            Assert.AreEqual(priorityQueue.Count, 0);

            Assert.IsFalse(priorityQueue.Remove("7"));
        }
Exemple #8
0
        public static int nthSuperUglyNumbers(int n, int[] primes)
        {
            PriorityQueue <long> q = new PriorityQueue <long>();

            q.Add(1L);
            foreach (int prime in primes)
            {
                q.Add((long)prime);
            }
            long ans = 0;

            while (n > 0)
            {
                long item = q.Poll();
                if (item != ans)
                {
                    n--;
                    foreach (int prime in primes)
                    {
                        q.Add(prime * item);
                    }
                }
                ans = item;
            }
            return((int)ans);
        }
Exemple #9
0
        static string solve(State startingState, State goalState)
        {
            var newStates = startingState.getPossibleNextStates();
            var visited   = new HashSet <State>();
            PriorityQueue <State> queue = new PriorityQueue <State>(new StateComparator());

            foreach (State state in newStates)
            {
                queue.Add(state);
            }
            while (queue.Count != 0)
            {
                var top = queue.Peek();
                queue.Remove(top);
                visited.Add(top);
                if (top.Equals(goalState))
                {
                    // done
                    return(getOutput(top));
                }
                newStates = top.getPossibleNextStates();
                foreach (State state in newStates)
                {
                    if (!visited.Contains(state))
                    {
                        queue.Add(state);
                    }
                }
            }
            return("failed to solve");
        }
Exemple #10
0
        public static int nthSuperUglyNumber(int n, int[] primes)
        {
            if (n == 1)
            {
                return(1);
            }

            long top = 0;
            long ans = 0;
            PriorityQueue <long> minHeap = new PriorityQueue <long>();

            foreach (int prime in primes)
            {
                minHeap.Add(prime);
            }

            n--;

            while (n > 0)
            {
                top = minHeap.Peek();
                minHeap.Poll();

                if (top != ans)
                {
                    n--;
                    foreach (int prime in primes)
                    {
                        minHeap.Add(top * prime);
                    }
                }
                ans = top;
            }
            return(Convert.ToInt32(top));
        }
        public void PopShouldReturnElementsByHigherPriority4()
        {
            var pq           = new PriorityQueue <int>();
            var addedNumbers = new List <int>();

            for (int i = 0; i < 50; i++)
            {
                if (i % 3 == 0)
                {
                    int numberToAdd = (int)(i / 2);
                    pq.Add(numberToAdd);
                    addedNumbers.Add(numberToAdd);
                    continue;
                }

                if (i % 2 == 0)
                {
                    int numberToAdd = (int)(i / 2);
                    pq.Add(numberToAdd);
                    addedNumbers.Add(numberToAdd);
                    continue;
                }

                pq.Add(i);
                addedNumbers.Add(i);
            }

            addedNumbers.Sort();
            addedNumbers.Reverse();
            for (int i = 0; i < pq.Count; i++)
            {
                var poppedNumber = pq.Pop();
                Assert.AreEqual(addedNumbers[i], poppedNumber);
            }
        }
Exemple #12
0
        /// <summary>
        /// Gets the maximum k values from an enumerable (by using a heap).
        /// </summary>
        /// <typeparam name="T">The type of an element in the enumerable.</typeparam>
        /// <param name="values">The enumerable of values.</param>
        /// <param name="k">The number of values to get.</param>
        /// <param name="comparer">The comparer to use for ordering.</param>
        /// <returns>The list of the maximum k values.</returns>
        public static IEnumerable <T> GetMaxKValues <T>(IEnumerable <T> values, int k, IComparer <T> comparer = null)
        {
            if (k < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(k), "The number of elements to get must not be negative.");
            }

            if (k == 0)
            {
                return(Enumerable.Empty <T>());
            }

            comparer = comparer ?? Comparer <T> .Default;
            var heap = new PriorityQueue <T>(comparer);

            foreach (var value in values)
            {
                if (heap.Count < k)
                {
                    heap.Add(value);
                }
                else if (comparer.Compare(value, heap[0]) > 0)
                {
                    heap.ExtractMinimum();
                    heap.Add(value);
                }
            }

            return(heap.Items.OrderByDescending(x => x, comparer));
        }
        public void PriorityQueueUpdateTest2()
        {
            var heap    = new PriorityQueue <TestPriorityQueueNode>(HeapType.Max, Allocator.Persistent);
            var maxItem = new TestPriorityQueueNode {
                Value = 10
            };

            heap.Add(new TestPriorityQueueNode {
                Value = 8
            });
            heap.Add(new TestPriorityQueueNode {
                Value = 2
            });
            heap.Add(new TestPriorityQueueNode {
                Value = 5
            });
            heap.Add(maxItem);
            heap.Add(new TestPriorityQueueNode {
                Value = 3
            });

            heap.Remove(maxItem);

            Assert.AreEqual(8, heap.Peek().Value);

            heap.Dispose();
        }
 public void RandomTest()
 {
     PriorityQueue<int> TestObject = new PriorityQueue<int>();
     Utilities.Random.Random Rand = new Utilities.Random.Random();
     int Value=0;
     for (int x = 0; x < 10; ++x)
     {
         Value=Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(Value, TestObject.Peek());
     }
     int HighestValue = TestObject.Peek();
     for (int x = 9; x >= 0; --x)
     {
         Value = Rand.Next();
         TestObject.Add(x, Value);
         Assert.Equal(HighestValue, TestObject.Peek());
     }
     int Count=0;
     foreach(int Priority in TestObject.Keys)
     {
         foreach(int Item in TestObject[Priority])
         {
             ++Count;
         }
     }
     Assert.Equal(20, Count);
 }
Exemple #15
0
        public Huffman(IEnumerable <T> values)
        {
            var counts        = new Dictionary <T, int>();
            var priorityQueue = new PriorityQueue <HuffmanNode <T> >();
            int valueCount    = 0;

            foreach (T value in values)
            {
                if (!counts.ContainsKey(value))
                {
                    counts[value] = 0;
                }
                counts[value]++;
                valueCount++;
            }

            foreach (T value in counts.Keys)
            {
                var node = new HuffmanNode <T>((double)counts[value] / valueCount, value);
                priorityQueue.Add(node);
                _leafDictionary[value] = node;
            }

            while (priorityQueue.Count > 1)
            {
                HuffmanNode <T> leftSon  = priorityQueue.Pop();
                HuffmanNode <T> rightSon = priorityQueue.Pop();
                var             parent   = new HuffmanNode <T>(leftSon, rightSon);
                priorityQueue.Add(parent);
            }

            _root        = priorityQueue.Pop();
            _root.IsZero = false;
        }
        // Dijkstra algorithm
        public void Dijkstra(string name)
        {
            ClearAll();

            // Register the startpoint of the algorithm
            Vertex start;

            if (!vertexMap.TryGetValue(name, out start))
            {
                throw new System.Exception();
            }

            // Create a priority queue
            PriorityQueue <Path> priorityQueue = new PriorityQueue <Path>();

            priorityQueue.Add(new Path(start, 0));
            start.dist = 0;

            // Amount of nodes seen
            int nodesSeen = 0;

            // Continue while the priority queue still has items and if not all vertexes are seen.
            while (priorityQueue.Size() > 0 && nodesSeen < vertexMap.Count)
            {
                // Get the vertex with the shortest path
                Path   path   = priorityQueue.Remove();
                Vertex vertex = path.dest;

                if (vertex.scratch != 0)
                {
                    continue;
                }

                // Scratch vertex
                vertex.scratch = 1;
                nodesSeen++;

                // Foreach all edges en set the distance of those nodes
                foreach (Edge edge in vertex.edges)
                {
                    Vertex destVertex = edge.dest;
                    double edgeCost   = edge.cost;

                    if (edgeCost < 0)
                    {
                        throw new System.Exception();
                    }

                    // Check if the distance is shorter
                    if (destVertex.dist > vertex.dist + edgeCost)
                    {
                        // Set the distance and the vertex where it came from
                        destVertex.dist = vertex.dist + edgeCost;
                        destVertex.prev = vertex;
                        // Add vertex to the priority queue
                        priorityQueue.Add(new Path(destVertex, destVertex.dist));
                    }
                }
            }
        }
        public void TestPriorityQueueClear()
        {
            PriorityQueue pq = new PriorityQueue();

            pq.Add(50);
            Assert.IsTrue("50".Equals(pq.PrintPreorder()));
            pq.Add(25);
            Assert.IsTrue("25 50".Equals(pq.PrintPreorder()));
            pq.Add(40);
            Assert.IsTrue("25 50 40".Equals(pq.PrintPreorder()));
            pq.Add(60);
            Assert.IsTrue("25 50 40 60".Equals(pq.PrintPreorder()));
            pq.Add(30);
            Assert.IsTrue("25 30 40 60 50".Equals(pq.PrintPreorder()));
            pq.Clear();
            Assert.IsTrue("".Equals(pq.PrintPreorder()));
            pq.Add(50);
            Assert.IsTrue("50".Equals(pq.PrintPreorder()));
            pq.Add(25);
            Assert.IsTrue("25 50".Equals(pq.PrintPreorder()));
            pq.Add(40);
            Assert.IsTrue("25 50 40".Equals(pq.PrintPreorder()));
            pq.Add(60);
            Assert.IsTrue("25 50 40 60".Equals(pq.PrintPreorder()));
            pq.Add(30);
            Assert.IsTrue("25 30 40 60 50".Equals(pq.PrintPreorder()));
        }
Exemple #18
0
        public void Simple()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum) { "5" };

            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Contains("5"));
            Assert.IsTrue(priorityQueue.Remove("5"));
            Assert.AreEqual(priorityQueue.Count, 0);

            priorityQueue.Add("6");
            priorityQueue.Add("7");
            priorityQueue.Add("2", 4);

            Assert.AreEqual(priorityQueue.Count, 3);
            Assert.IsTrue(priorityQueue.Contains("6"));
            Assert.IsTrue(priorityQueue.Contains("7"));
            Assert.IsTrue(priorityQueue.Contains("2"));

            Assert.IsFalse(priorityQueue.Remove("8"));

            Assert.IsTrue(priorityQueue.Remove("7"));
            Assert.AreEqual(priorityQueue.Count, 2);
            Assert.IsTrue(priorityQueue.Remove("2"));
            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Remove("6"));
            Assert.AreEqual(priorityQueue.Count, 0);

            Assert.IsFalse(priorityQueue.Remove("7"));
        }
Exemple #19
0
        public void TestThatPop_Works()
        {
            PriorityQueue <int> que = new PriorityQueue <int>();

            int[] poppedNumbers   = new int[10];
            int[] expectedNumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            que.Add(10);
            que.Add(9);
            que.Add(8);
            que.Add(7);
            que.Add(6);
            que.Add(5);
            que.Add(4);
            que.Add(3);
            que.Add(2);
            que.Add(1);

            for (int i = 0; i < poppedNumbers.Length; i++)
            {
                poppedNumbers[i] = que.Pop();
            }


            CollectionAssert.AreEqual(expectedNumbers, poppedNumbers);
        }
Exemple #20
0
        public void PriorityQueuePriorityGreaterThanLeftChildTauForIndexNotZero()
        {
            const int size = 5;
            var       pq   = new PriorityQueue <int>(size);

            Assert.AreEqual(size, pq.Size);

            pq.Add(0.0, 0);
            pq.Add(5.0, 1);
            pq.Add(3.0, 2);
            pq.Add(4.0, 3);
            pq.Add(2.0, 4);
            PrintNodes(pq);

            pq.UpdateIndex(3.5, 1);
            pq.UpdateIndex(2.5, 1);
            pq.UpdateIndex(3.5, 0);
            PrintNodes(pq);

            PriorityQueue <int> .Node <int>[] nodes = pq.Nodes;
            Assert.AreEqual(2, nodes[0].Priority);
            Assert.AreEqual(2.5, nodes[1].Priority);
            Assert.AreEqual(3, nodes[2].Priority);
            Assert.AreEqual(3.5, nodes[3].Priority);
            Assert.AreEqual(4, nodes[4].Priority);
        }
Exemple #21
0
        public static IDictionary <string, UniversalGraphNodeData> StartDijkstra(IEnumerable <MappedNode> mapedEnumerable, string keyFrom)
        {
            var queue = new PriorityQueue <string> {
                { 0, keyFrom }
            };

            var dataDict  = new Dictionary <string, UniversalGraphNodeData>();
            var mapedList = mapedEnumerable.ToList();

            foreach (var mappedNode in mapedList)
            {
                dataDict.Add(mappedNode.Node.Key, new UniversalGraphNodeData {
                    Node = mappedNode
                });
            }

            dataDict[keyFrom].IsVisited = true;
            dataDict[keyFrom].Cost      = 0;

            while (queue.Count != 0)
            {                                // пока очередь не пуста
                var nodeName  = queue.Pop(); // извлечь первый элемент в очереди
                var nextMaped = dataDict[nodeName].Node;

                foreach (var link in nextMaped.Links)
                {    // все преемники текущего узла, ...
                    var to = link.GetTo(nodeName);

                    if (dataDict[to].IsVisited == false)
                    {
                        var toNodeCost   = int.Parse(link.Text);
                        var selfCost     = dataDict[nodeName].Cost;
                        var newTotalCost = toNodeCost + selfCost;

                        if (dataDict[to].Cost == -1)
                        {
                            queue.Add(newTotalCost * -1, to);
                            dataDict[to].Cost = newTotalCost;
                        }
                        else if (dataDict[to].Cost > newTotalCost)
                        {
                            queue.Remove(dataDict[to].Cost * -1);
                            dataDict[to].Cost = newTotalCost;
                            queue.Add(newTotalCost * -1, to);
                        }
                        else
                        {
                            continue;
                        }

                        dataDict[to].ParentMappedNode = nextMaped;
                        dataDict[to].ParentLink       = link;
                    }
                }
                dataDict[nodeName].IsVisited = true;
            }

            return(dataDict);
        }
Exemple #22
0
        public EventTimerEvent AddTime(int milliseconds, Action then, int interval = 0)
        {
            DateTime time = DateTime.Now.AddMilliseconds(milliseconds);
            var      e    = new EventTimerEvent(then, interval);

            _queue.Add(new KeyValuePair <DateTime, EventTimerEvent>(time, e));
            return(e);
        }
    private PriorityQueue openPriorityQueue = new PriorityQueue();     // a visitar

    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);

        SearchState start = new SearchState(startNode, 0);

        openPriorityQueue.Add(start, 0);
    }
Exemple #24
0
        public void WithNonComparableItem()
        {
            var priorityQueue = new PriorityQueue <string, NonComparable>(PriorityQueueType.Minimum);

            Assert.AreEqual(priorityQueue.Count, 0);

            priorityQueue.Add("a", new NonComparable());
            Assert.Throws <ArgumentException>(() => priorityQueue.Add("b", new NonComparable()));
        }
Exemple #25
0
        public FortunesAlgorithm(Point2D[] points)
        {
            m_initialPoints = points;

            foreach (var point in points)
            {
                m_queue.Add(new VSiteEvent(point));
            }
        }
Exemple #26
0
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);

        SearchState start = new SearchState(startNode, 0);

        p_queue.Add(start, (int)start.f);        // 0 ???
    }
Exemple #27
0
    public List <Vector3> FindPath(Vector3 start, Vector3 goal)
    {
        Node goalNode  = point2Grid(goal);
        Node startNode = point2Grid(start);

        PriorityQueue <Node> frontier = new PriorityQueue <Node>();

        frontier.Add(startNode, 0);
        Dictionary <Node, float> cost_so_far = new Dictionary <Node, float>();
        Dictionary <Node, Node>  came_from   = new Dictionary <Node, Node>();

        List <Vector3> result = new List <Vector3>();

        came_from[startNode]   = startNode;
        cost_so_far[startNode] = 0;

        if (!goalNode.walkable)
        {
            return(result);
        }

        while (!frontier.Empty())
        {
            //TODO: implementar heap
            Node current = frontier.Get();

            if (current == goalNode)
            {
                break;
            }

            foreach (Node next in neighbours(current))
            {
                float new_cost = cost_so_far[current] + 1;
                if (!cost_so_far.ContainsKey(next) || new_cost < cost_so_far[next])
                {
                    cost_so_far[next] = new_cost;
                    float priority = new_cost + heuristic(next, goalNode);
                    frontier.Add(next, priority);
                    came_from[next] = current;
                }
            }
        }

        if (came_from.ContainsKey(goalNode))
        {
            Node currentNode = goalNode;
            while (currentNode != startNode)
            {
                result.Add(currentNode.worldPosition);
                currentNode = came_from[currentNode];
            }
        }
        result.Reverse();
        return(result);
    }
Exemple #28
0
        public void Run(Vector2 seed)
        {
            //Here's the algorithm:
            //1. Start at the seed position.
            //2. Trace from that seed across the "field" defined by the road ortho bases until the end is hit or something else stops it.
            //3. If the traced line fits certain constraints, then it is now a road
            //     and the various discrete points it stopped at along the way
            //     are fed in as new potential seeds to start from.
            //   Each new seed point has a "priority" based on something (e.x. a population density map).
            //4. As long as we have new seeds to consider, pick the seed with the highest priority and GOTO 2.

            HashSet <VertexSeed>       alreadyTried = new HashSet <VertexSeed>();
            PriorityQueue <VertexSeed> candidates   = new PriorityQueue <VertexSeed>(false);

            float  priority = 1.0f;// GetPriority(seed);
            Vertex v1       = new Vertex(seed);

            for (int dir = -1; dir < 2; dir += 2)
            {
                VertexSeed vs = new VertexSeed(v1, true, dir);
                candidates.Add(vs, priority);
                alreadyTried.Add(vs);
            }

            while (candidates.Count > 0)
            {
                VertexSeed vs = candidates.Peek(out priority);
                candidates.Pop();

                Road rd = Trace(vs.V, vs.UseMajor, vs.Dir);

                if (rd != null)
                {
                    //Add the road to the city, and add the road's vertices to the new road seed collection.
                    Roads.Add(rd);
                    for (int i = 0; i < rd.Points.Count; ++i)
                    {
                        priority = GetPriority(rd.Points[i].Pos);

                        VertexSeed vSeed = new VertexSeed(rd.Points[i], !vs.UseMajor, 1);
                        if (!alreadyTried.Contains(vSeed))
                        {
                            candidates.Add(vSeed, priority);
                            alreadyTried.Add(vSeed);
                        }

                        vSeed.Dir = -1;
                        if (!alreadyTried.Contains(vSeed))
                        {
                            candidates.Add(vSeed, priority);
                            alreadyTried.Add(vSeed);
                        }
                    }
                }
            }
        }
Exemple #29
0
    public string RearrangeString(string s, int k)
    {
        if (string.IsNullOrEmpty(s))
        {
            return("");
        }

        Dictionary <char, int> table = new Dictionary <char, int>();

        foreach (var ch in s)
        {
            if (table.ContainsKey(ch))
            {
                table[ch] = table[ch] + 1;
            }
            else
            {
                table[ch] = 1;
            }
        }

        PriorityQueue <Bag> minQue = new PriorityQueue <Bag>();

        foreach (var kv in table)
        {
            minQue.Add(new Bag(kv.Key, kv.Value));
        }

        List <char> result = new List <char>();
        List <Bag>  tmp    = new List <Bag>();

        while (minQue.Count > 0)
        {
            Bag item = minQue.Poll();
            result.Add(item.Data);
            item.Count--;
            tmp.Add(item);

            if (tmp.Count < k)
            {
                continue;
            }

            Bag a = tmp[0];
            tmp.RemoveAt(0);
            if (a.Count > 0)
            {
                minQue.Add(a);
            }
        }
        if (result.Count != s.Length)
        {
            return("");
        }
        return(new string(result.ToArray()));
    }
Exemple #30
0
    protected IDictionary <IGraphNode <T>, IGraphEdge <T> > RelaxEdges(IGraph <T> graph, IGraphNode <T> node, float initialCost = 0)
    {
        PriorityQueue <QueueType> openNodes = new PriorityQueue <QueueType>(graph.NodeCount);
        IDictionary <IGraphNode <T>, QueueType>       priorityQueueLocator = new Dictionary <IGraphNode <T>, QueueType>();
        IDictionary <IGraphNode <T>, IGraphEdge <T> > parents = new Dictionary <IGraphNode <T>, IGraphEdge <T> >();
        HashSet <IGraphNode <T> > closedNodes = new HashSet <IGraphNode <T> >();

        QueueType nodePair = new QueueType(initialCost, node);

        openNodes.Add(nodePair);
        priorityQueueLocator[node] = nodePair;

        while (openNodes.Count > 0)
        {
            nodePair = openNodes.Pop();
            float baseCost = nodePair.First;
            node = nodePair.Second;

            if (ShouldTerminate(node))
            {
                break;
            }

            foreach (IGraphEdge <T> edge in graph.GetEdges(node))
            {
                if (closedNodes.Contains(edge.node2))
                {
                    continue;
                }

                float          cost = GetCost(baseCost, edge);
                IGraphEdge <T> currentEdge;
                if (!parents.TryGetValue(edge.node2, out currentEdge) ||
                    cost < currentEdge.weight)
                {
                    parents[edge.node2] = edge;
                    nodePair            = new QueueType(cost, edge.node2);
                    QueueType oldPair;
                    if (priorityQueueLocator.TryGetValue(edge.node2, out oldPair) &&
                        openNodes.Contains(oldPair))
                    {
                        openNodes.UpdatePosition(oldPair, nodePair);
                    }
                    else
                    {
                        openNodes.Add(nodePair);
                    }
                    priorityQueueLocator[edge.node2] = nodePair;
                }
            }

            closedNodes.Add(node);
        }

        return(parents);
    }
        public void AddExample()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum);
            priorityQueue.Add("cat");
            priorityQueue.Add("dog");
            priorityQueue.Add("canary");

            // There will be 3 items in the priorityQueue.
            Assert.AreEqual(3, priorityQueue.Count);
        }
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);

        //inicializa a arvore de procura com o estado (no) inicial do problema
        SearchState start = new SearchState(startNode, 0);

        p_queue.Add(start, (int)start.f);
    }
Exemple #33
0
        public int GetDistanceMovement(int[] from, int[] to)
        {
            PriorityQueue <PriorityCoordinates> frontier = new PriorityQueue <PriorityCoordinates>();

            Dictionary <int[], int[]> cameFrom = new Dictionary <int[], int[]>
                                                     (new ArrayEqualityComparer())
            {
                { from, null }
            };
            Dictionary <int[], int> distSoFar = new Dictionary <int[], int>
                                                    (new ArrayEqualityComparer())
            {
                { from, 0 }
            };

            frontier.Add(new PriorityCoordinates(from, 0));
            while (frontier.Count > 0)
            {
                int[] currCoords = frontier.Take().Coordinates;

                if (currCoords.SequenceEqual(to))
                {
                    break;
                }

                int[][] neighbors = GetPassableNeighborsFor(currCoords);
                foreach (int[] next in neighbors)
                {
                    int  oldDist          = distSoFar[currCoords];
                    int  newDist          = oldDist + 1;
                    bool foundShorterPath = false;
                    if (!distSoFar.ContainsKey(next))
                    {
                        foundShorterPath = true;
                    }
                    else
                    {
                        foundShorterPath |= distSoFar[next] > newDist;
                    }

                    if (foundShorterPath)
                    {
                        if (distSoFar.ContainsKey(next))
                        {
                            distSoFar.Remove(next);
                        }
                        distSoFar.Add(next, newDist);
                        int priority = newDist + GetPureDistance(next, to);
                        frontier.Add(new PriorityCoordinates(next, priority));
                        cameFrom.Add(next, currCoords);
                    }
                }
            }
            return(distSoFar[to]);
        }
        public void AddPriorityExample()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum);
            priorityQueue.Add("cat", 2);
            priorityQueue.Add("canary", 1);
            priorityQueue.Add("dog", 3);

            // There will be 3 items in the priorityQueue.
            Assert.AreEqual(3, priorityQueue.Count);

            // "canary" will be at the top as it has the highest priority
            Assert.AreEqual("canary", priorityQueue.Peek());
        }
Exemple #35
0
        public void Simple()
        {
            var priorityQueue = new PriorityQueue<int, int>(PriorityQueueType.Minimum);
            Assert.AreEqual(priorityQueue.Count, 0);

            priorityQueue.Add(4);
            Assert.AreEqual(priorityQueue.Count, 1);

            priorityQueue.Add(99);
            Assert.AreEqual(priorityQueue.Count, 2);

            priorityQueue.Clear();
            Assert.AreEqual(priorityQueue.Count, 0);
        }
Exemple #36
0
        public void Simple()
        {
            var priorityQueue = new PriorityQueue<int, int>(PriorityQueueType.Maximum);
            Assert.IsFalse(priorityQueue.IsReadOnly);

            priorityQueue.Add(4);
            Assert.IsFalse(priorityQueue.IsReadOnly);

            priorityQueue.Add(99);
            Assert.IsFalse(priorityQueue.IsReadOnly);

            priorityQueue.Clear();
            Assert.IsFalse(priorityQueue.IsReadOnly);
        }
        public static void Main(string[] args)
        {
            var priorityQueue = new PriorityQueue<int>();

            priorityQueue.Add(1);
            priorityQueue.Add(2);
            priorityQueue.Add(513);
            priorityQueue.Add(51);
            priorityQueue.Add(1551);

            while (priorityQueue.Count > 0)
            {
                Console.WriteLine(priorityQueue.Dequeue());
            }
        }
Exemple #38
0
        public void PriorityQueueGeneralTest()
        {
            var queue = new PriorityQueue<int>();

            Assert.IsTrue(queue.Empty, "New queue should start out empty.");
            Assert.Throws<InvalidOperationException>(() => queue.Peek(), "Peeking at an empty queue should throw.");
            Assert.Throws<InvalidOperationException>(() => queue.Pop(), "Popping an empty queue should throw.");

            foreach (var value in new[] { 4, 3, 5, 1, 2 })
            {
                queue.Add(value);
                Assert.IsFalse(queue.Empty, "Queue should not be empty - items have been added.");
            }

            foreach (var value in new[] { 1, 2, 3, 4, 5 })
            {
                Assert.AreEqual(value, queue.Peek(), "Peek returned the wrong item - should be in order.");
                Assert.IsFalse(queue.Empty, "Queue should not be empty yet.");
                Assert.AreEqual(value, queue.Pop(), "Pop returned the wrong item - should be in order.");
            }

            Assert.IsTrue(queue.Empty, "Queue should now be empty.");
            Assert.Throws<InvalidOperationException>(() => queue.Peek(), "Peeking at an empty queue should throw.");
            Assert.Throws<InvalidOperationException>(() => queue.Pop(), "Popping an empty queue should throw.");
        }
Exemple #39
0
    /* Task 1:  
     * Implement a class PriorityQueue<T> based on the data structure "binary heap".
     */

    static void Main(string[] args)
    {
        var prioQueue = new PriorityQueue<int>();

        prioQueue.Add(25);
        prioQueue.Add(15);
        prioQueue.Add(105);
        prioQueue.Add(5);
        prioQueue.Add(35);

        Console.WriteLine(prioQueue.Count());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
    }
Exemple #40
0
        public void Simple()
        {
            var priorityQueue1 = new PriorityQueue<int, int>(PriorityQueueType.Minimum) { 4 };

            Assert.AreEqual(priorityQueue1.Count, 1);
            Assert.AreEqual(priorityQueue1.Dequeue(), 4);

            priorityQueue1.Add(5);
            priorityQueue1.Add(6, 2);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            priorityQueue1.Add(6, 2);
            priorityQueue1.Add(5);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            var priorityQueue2 = new PriorityQueue<string, int>(PriorityQueueType.Minimum)
                                     {
                                         {"a", 1},
                                         {"b", 2},
                                         {"c", 3},
                                         {"d", 4},
                                         {"e", 5},
                                         {"f", 6},
                                         {"z", 6},
                                         {"y", 5},
                                         {"x", 4},
                                         {"w", 3},
                                         {"v", 2},
                                         {"u", 1},
                                         {"z", 1},
                                         {"y", 2},
                                         {"x", 3},
                                         {"w", 4},
                                         {"v", 5},
                                         {"u", 6}
                                     };

            Assert.AreEqual(priorityQueue2.Count, 18);

            priorityQueue2.Clear();

            Assert.AreEqual(priorityQueue2.Count, 0);
        }
Exemple #41
0
        private static void Main()
        {
            var priorityQueue = new PriorityQueue<int>();
            priorityQueue.Add(1);
            priorityQueue.Add(1);
            priorityQueue.Add(3);
            priorityQueue.Add(1);
            priorityQueue.Add(3);
            priorityQueue.Add(10);
            priorityQueue.Add(2);
            priorityQueue.Add(2);
            priorityQueue.Add(3);
            priorityQueue.Add(2);

            while (priorityQueue.Count != 0)
            {
                Console.WriteLine(priorityQueue.Dequeue());
            }
        }
Exemple #42
0
        public void WithPriority()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum);

            int priority;

            priorityQueue.Add("5", 3);
            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Contains("5"));
            Assert.IsTrue(priorityQueue.Remove("5", out priority));
            Assert.AreEqual(priority, 3);

            Assert.AreEqual(priorityQueue.Count, 0);

            priorityQueue.Add("6");
            priorityQueue.Add("7");
            priorityQueue.Add("2", 4);

            Assert.AreEqual(priorityQueue.Count, 3);
            Assert.IsTrue(priorityQueue.Contains("6"));
            Assert.IsTrue(priorityQueue.Contains("7"));
            Assert.IsTrue(priorityQueue.Contains("2"));

            Assert.IsFalse(priorityQueue.Remove("8", out priority));

            Assert.IsTrue(priorityQueue.Remove("7", out priority));
            Assert.AreEqual(priority, 0);
            Assert.AreEqual(priorityQueue.Count, 2);

            Assert.IsTrue(priorityQueue.Remove("2", out priority));
            Assert.AreEqual(priority, 4);

            Assert.AreEqual(priorityQueue.Count, 1);
            Assert.IsTrue(priorityQueue.Remove("6", out priority));
            Assert.AreEqual(priority, 0);
            Assert.AreEqual(priorityQueue.Count, 0);

            Assert.IsFalse(priorityQueue.Remove("7", out priority));
        }
 public void TestPriorityQueueCount()
 {
     PriorityQueue<int> pq = new PriorityQueue<int>();
     pq.Add(5);
     pq.Add(6);
     pq.Add(3);
     pq.Add(7);
     pq.Add(11);
     pq.Add(-5);
     pq.GetTop();
     pq.GetTop();
     Assert.AreEqual(4, pq.Count, "Incorrectly counting the queue elements");
 }
 public void TestPriorityQueueOrder_2()
 {
     PriorityQueue<int> pq = new PriorityQueue<int>();
     pq.Add(5);
     pq.Add(6);
     pq.Add(3);
     pq.Add(7);
     Assert.AreEqual(3, pq.GetTop(), "Incorrect element returned!");
     pq.Add(11);
     pq.Add(-5);
     Assert.AreEqual(-5, pq.GetTop(), "Incorrect element returned!");
     pq.Add(6);
     Assert.AreEqual(5, pq.GetTop(), "Incorrect element returned!");
     Assert.AreEqual(6, pq.GetTop(), "Incorrect element returned!");
     Assert.AreEqual(6, pq.GetTop(), "Incorrect element returned!");
     Assert.AreEqual(7, pq.GetTop(), "Incorrect element returned!");
     Assert.AreEqual(11, pq.GetTop(), "Incorrect element returned!");
 }
        public void TestPriorityQueueOrder_1()
        {
            PriorityQueue<int> pq = new PriorityQueue<int>();
            pq.Add(5);
            pq.Add(6);
            pq.Add(3);
            pq.Add(7);
            pq.Add(11);
            pq.Add(-5);

            Assert.AreEqual(-5, pq.GetTop());
            Assert.AreEqual(3, pq.GetTop());
            Assert.AreEqual(5, pq.GetTop());
            Assert.AreEqual(6, pq.GetTop());
            Assert.AreEqual(7, pq.GetTop());
            Assert.AreEqual(11, pq.GetTop());
        }
        public void TestWithPrimitiveType()
        {
            var priorityQueueInts = new PriorityQueue<int>();

            priorityQueueInts.Add(5);
            priorityQueueInts.Add(10);
            priorityQueueInts.Add(-5);
            priorityQueueInts.Add(1);
            priorityQueueInts.Add(13);
            priorityQueueInts.Add(13);
            priorityQueueInts.Add(0);
            priorityQueueInts.Add(25);

            var numbersActualOrder = new List<int>();

            while (priorityQueueInts.Count > 0)
            {
                numbersActualOrder.Add(priorityQueueInts.RemoveFirst());
            }

            var numbersExpectedOrder = new List<int>() { -5, 0, 1, 5, 10, 13, 13, 25 };

            CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
        }
    static void Main()
    {
        var priQueue = new PriorityQueue<int>();

        priQueue.Add(-5);
        priQueue.Add(7);
        priQueue.Add(9);
        priQueue.Add(5);
        priQueue.Add(1);
        priQueue.Add(8);

        priQueue.Remove();

        foreach (var el in priQueue)
        {
            Console.WriteLine(el);
        }
        Console.WriteLine("Element count: {0}, Capacity: {1}", priQueue.Count, priQueue.Capacity);

        priQueue.Clear();
        Console.WriteLine("Element count: {0}, Capacity: {1}", priQueue.Count, priQueue.Capacity);
    }
        public void TestWithClassHumanImplementsIComparableByAge()
        {
            // Test with class Human implements IComparable (by Age):
            var priorityQueueHumans = new PriorityQueue<Human>();

            priorityQueueHumans.Add(new Human("Ivan", 25));
            priorityQueueHumans.Add(new Human("Georgi", 13));
            priorityQueueHumans.Add(new Human("Cvetelina", 18));
            priorityQueueHumans.Add(new Human("Plamena", 22));
            priorityQueueHumans.Add(new Human("Gergana", 23));
            priorityQueueHumans.Add(new Human("Qna", 21));

            var numbersActualOrder = new List<string>();

            while (priorityQueueHumans.Count > 0)
            {
                numbersActualOrder.Add(priorityQueueHumans.RemoveFirst().Name);
            }

            var numbersExpectedOrder = new List<string>() { "Georgi", "Cvetelina", "Qna", "Plamena", "Gergana", "Ivan" };

            CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
        }
Exemple #49
0
    public Node[] FindPath(Node source, Node destination)
    {
        //Initialize single source
        float[] d = new float[nodos.Count];

        for (int i = 0; i < d.Length; i++) {
            d[i] = Mathf.Infinity;
        }
        d[node2int[source]] = 0.0f;
        Node[] p = new Node[nodos.Count];

        //Dijkstra
        PriorityQueue<float, Node> q = new PriorityQueue<float, Node>(nodos.Count);

        foreach(Node n in nodos){
            q.Add(new KeyValuePair<float, Node>(d[node2int[n]], n));
        }

        while(q.Count > 0){
            Node u = q.DequeueValue();
            for(int i = 0; i < nodos.Count; i++){
                if(i != node2int[u] && adj[node2int[u], i] != Mathf.Infinity){
                    //Relaxation
                    if(d[i] > d[node2int[u]] + adj[node2int[u], i]){
                        //Debug.Log("Contiene" + q.Contains(new KeyValuePair<float, Node>(d[i], nodos[i])));
                        q.Remove(new KeyValuePair<float, Node>(d[i], nodos[i]));

                        d[i] = d[node2int[u]] + adj[node2int[u], i];
                        p[i] = u;
                        //Debug.Log(i + " " + d[i]);
                        //Update values
                        q.Add(new KeyValuePair<float, Node>(d[i], nodos[i]));
                    }
                }
            }
            //Debug.Log("Iteration" + node2int[u]);
        }

        Stack<Node> path = new Stack<Node>();

        Node prev = destination;

        while(prev != source){
            if(d[node2int[prev]] == Mathf.Infinity){
                throw new Exception("Unreachable node");
            }
            path.Push(prev);
            prev = p[node2int[prev]];
        }

        path.Push(source);
        return path.ToArray();
    }
    public void AStarSearch(Vector2 _Source, Vector2 _Target, bool _AllowUnwalkable)
    {
        m_SourceIndex = PointDatabase.Instance.GetIdealPoint(_Source,_Target).Index;
        m_TargetIndex = PointDatabase.Instance.GetClosestPointToPosition(_Target,_AllowUnwalkable).Index;

        List<Point> PointList = PointDatabase.Instance.ReturnDatabaseAsList();
        m_SearchFrontier = new Dictionary<string,Edge>();//store all points that are being searched
        m_ShortestPath = new Dictionary<string,Edge>();
        m_fCost = new Dictionary<string,float>();//cumulative cost to current node + heuristic cost from current node to target node
        m_gCost = new Dictionary<string,float>();//cumulative cost from the source node to the current node
        InitializeDictionaries();

        PriorityQueue priorityQueue = new PriorityQueue(m_fCost);
        priorityQueue.Add(m_SourceIndex);

        while(priorityQueue.Count() != 0)
        {
            string nextClosestPoint = priorityQueue.Dequeue();

            m_ShortestPath[nextClosestPoint] = m_SearchFrontier[nextClosestPoint];

            if(nextClosestPoint == m_TargetIndex)
            {
                return;
            }

            foreach(Edge edge in m_Database.Database[nextClosestPoint].Edges)
            {
                //heuristic cost from current node to target node
                float HCost = CalculateDistanceBetweenPoints(edge.End,m_Database.Database[m_TargetIndex]);
                //cumulative cost from the start node to the current node
                float GCost = m_gCost[nextClosestPoint] + edge.Cost;

                if(_AllowUnwalkable == false)
                {
                    if(m_SearchFrontier[edge.End.Index] == null && edge.End.Walkable == true)
                    {
                        m_fCost[edge.End.Index] = HCost + GCost;
                        m_gCost[edge.End.Index] = GCost;
                        priorityQueue.Add(edge.End.Index);
                        m_SearchFrontier[edge.End.Index] = edge;
                    }
                    else if(GCost < m_gCost[edge.End.Index] && m_ShortestPath[edge.End.Index] == null && edge.End.Walkable == true)
                    {
                        m_fCost[edge.End.Index] = HCost + GCost;
                        m_gCost[edge.End.Index] = GCost;
                        priorityQueue.Add(edge.End.Index);
                        m_SearchFrontier[edge.End.Index] = edge;
                    }
                }
                else
                {
                    if(m_SearchFrontier[edge.End.Index] == null)
                    {
                        m_fCost[edge.End.Index] = HCost + GCost;
                        m_gCost[edge.End.Index] = GCost;
                        priorityQueue.Add(edge.End.Index);
                        m_SearchFrontier[edge.End.Index] = edge;
                    }
                    else if(GCost < m_gCost[edge.End.Index] && m_ShortestPath[edge.End.Index] == null)
                    {
                        m_fCost[edge.End.Index] = HCost + GCost;
                        m_gCost[edge.End.Index] = GCost;
                        priorityQueue.Add(edge.End.Index);
                        m_SearchFrontier[edge.End.Index] = edge;
                    }
                }
            }
        }
    }
Exemple #51
0
    public static Vector3[] FindPath(int[] start, int[] end)
    {
        PathManager mgr = GetInstance ();

        Vector3[] outPath;
        if (mgr.QueryCache (start, end, out outPath)) {
            return outPath;
        }

        int pathSearched = 0;

        GridManager grid = GridManager.GetInstance ();
        if (!grid.HasSurface (start) || !grid.HasSurface (end)) {
            return null;
        }

        List<Node> closed = new List<Node> ();
        PriorityQueue<Node> open = new PriorityQueue<Node> ();
        open.comparator = Node.Comparison;

        Vector3 goal = grid.GridCenter (end);

        Node s = new Node ();
        s.edge = null;
        s.g_score = 0.0f;
        s.h_score = mgr.SqDist (s.p, goal);
        s.f_score = s.h_score;
        s.p = grid.GridCenter (start);

        open.Add (s);

        while (!open.Empty ()) {
            Node node = open.Top;
            open.Remove (open.Top);

            // if it ends, end.
            if (node.p == goal) {
                List<Vector3> path = new List<Vector3> ();
                mgr.ReconstructPath (node, path);
                Vector3[] outpath = path.ToArray ();
                mgr.CachePath (start, end, outpath);
                return outpath;
            }

            closed.Add (node);

            List<Vector3> neighbors = mgr.Neighbors(node.p);
            foreach (Vector3 n in neighbors) {
                if (closed.FindIndex ((a) => a.p == n) >= 0) {
                    continue;
                }
                float temp_g = node.g_score + mgr.SqDist(node.p, n);
                Node f = open.Find ((a) => a.p == n);
                if (f == null) {
                    f = new Node ();
                    f.edge = node;
                    f.g_score = temp_g;
                    f.h_score = mgr.SqDist(n, goal);
                    f.f_score = f.g_score + f.h_score;
                    f.p = n;
                    open.Add (f);
                } else if (temp_g < f.g_score) {
                    f.edge = node;
                    f.g_score = temp_g;
                    f.f_score = f.g_score + f.h_score;
                    open.Update (f);
                }
            }
            if (pathSearched >= mgr.pathSearchLimit) {
                return null;
            } else {
                pathSearched ++;
            }
        }
        return null;
    }
Exemple #52
0
    private void CreatePath(Vertex2 start)
    {
        PriorityQueue frontier = new PriorityQueue ();
        frontier.Add (0, start);
        Dictionary<Vertex2, Vertex2> from = new Dictionary<Vertex2, Vertex2> ();
        Dictionary<Vertex2, double> cost = new Dictionary<Vertex2, double> ();
        cost [start] = 0;
        from [start] = null;
        Vertex2 end = null;

        while (!frontier.IsEmpty()) {
            var current = frontier.GetMin ();
            if(IsGoal(current)) {
                end = current;
                break;
            }

            foreach(PathNode neighbor in GetNeighbors(current)) {
                Vertex2 vNeighbor = neighbor.location;
                double newCost = cost[current] + neighbor.cost;
                if(!cost.ContainsKey(vNeighbor) || newCost < cost[vNeighbor]) {
                    cost[vNeighbor] = newCost;
                    frontier.Add(newCost, vNeighbor);
                    from[vNeighbor] = current;
                }
            }
        }

        if (end != null) {
            Vertex2 current = end;
            while(!current.Equals(start)) {
                EnablePoint(current);
                current = from[current];
            }
        }
    }
Exemple #53
0
        public static bool GetShortestPath(GridNode i_start, GridNode i_end, bool isDiagonal, out List<GridNode> o_path, out List<GridNode> o_open)
        {
            o_path = new List<GridNode>();
            o_open = new List<GridNode>();

            IDictionary<GridNode, GridNode> path = new Dictionary<GridNode, GridNode>();
            IDictionary<GridNode, float> open = new Dictionary<GridNode, float>();

            PriorityQueue<float, GridNode> priorityQueue = new PriorityQueue<float, GridNode>(30 * 30, Comparer<float>.Default);

            priorityQueue.Add(new KeyValuePair<float, GridNode>(GetDistance(i_start, i_end, isDiagonal), i_start));
            open.Add(new KeyValuePair<GridNode, float>(i_start, 0));

            bool succeed = false;
            while (!priorityQueue.IsEmpty)
            {
                KeyValuePair<float, GridNode> current = priorityQueue.Peek();
                GridNode currentNode = current.Value;
                float currentCost;
                if (!open.TryGetValue(currentNode, out currentCost))
                {
                    Debug.Assert(false);
                }

                if (currentNode == i_end)
                {
                    succeed = true;
                    break;
                }

                foreach (GridNode neighbour in currentNode.GetNeighbors(isDiagonal))
                {
                    if (neighbour.Passable)
                    {
                        float newCost = currentCost + GetCost(currentNode, neighbour, isDiagonal);
                        float oldCost;
                        if (!open.TryGetValue(neighbour, out oldCost))
                        {
                            path.Add(neighbour, currentNode);
                            open.Add(neighbour, newCost);
                            float dist = GetDistance(neighbour, i_end, isDiagonal);
                            priorityQueue.Add(new KeyValuePair<float, GridNode>(newCost + dist, neighbour));
                        }
                        else if (newCost < oldCost)
                        {
                            path[neighbour] = currentNode;
                            open[neighbour] = newCost;
                            float dist = GetDistance(neighbour, i_end, isDiagonal);
                            priorityQueue.Remove(new KeyValuePair<float, GridNode>(oldCost + dist, neighbour));
                            priorityQueue.Add(new KeyValuePair<float, GridNode>(newCost + dist, neighbour));
                        }
                    }
                }

                priorityQueue.Remove(current);
            }

            if (succeed)
            {

                GridNode currentNode = i_end;
                o_path.Add(currentNode);
                while (path.ContainsKey(currentNode))
                {
                    currentNode = path[currentNode];
                    o_path.Add(currentNode);
                }
                o_path.Reverse();

            }

            o_open = open.Keys.ToList();

            return succeed;
        }
    public void testCase3()
    {
        //測試PripriorityQueue
        AsiaBoy[] b = new AsiaBoy[10];
        b[0] = new AsiaBoy(20);
        b[1] = new AsiaBoy(14);
        b[2] = new AsiaBoy(0);
        b[3] = new AsiaBoy(3);
        b[4] = new AsiaBoy(6);
        b[5] = new AsiaBoy(8);
        b[6] = new AsiaBoy(12);
        b[7] = new AsiaBoy(11);
        b[8] = new AsiaBoy(4);
        b[9] = new AsiaBoy(6);
        PriorityQueue<AsiaBoy> q = new PriorityQueue<AsiaBoy>();

        foreach (AsiaBoy boy in b)
            q.Add(boy, boy.length);

        q.popup();

        List<QueueElement<AsiaBoy>>.Enumerator it = q.getEnumerator();
        string message="";
        while (it.MoveNext())
        {
            AsiaBoy boy = it.Current.obj;
            message += "["+boy.length+ "]";
        }

        Debug.Log("[inside PripriorityQueue] = "+message);
    }
Exemple #55
0
    void Awake()
    {
        if (_instance != null) {
            Debug.LogError ("Instance should be null");
        }
        _instance = this;

        priorityQueue = new PriorityQueue<TimerMessage> ();
        priorityQueue.comparator = Comparison;

        for (int i = 0; i < messages.Length; i ++) {
            messages[i].gameObject = null;
            messages[i].nextTime = Time.time + messages[i].secondsBetween;

            priorityQueue.Add (messages[i]);
        }

        if (!priorityQueue.Empty ()) {
            // StartCoroutine (Schedule());
        } else {
            enabled = false;
        }
    }
Exemple #56
0
        /// <summary>
        ///  solve the problem.  This is the entry point for the solver when the run button is clicked
        /// right now it just picks a simple solution. 
        /// </summary>
        public void solveProblem()
        {
            stopwatch = new Stopwatch();
            stopwatch.Start();
            bssf = generateInitialBSSF();
            State s = initState();
            agenda = new PriorityQueue<double, State>();
            agenda.Add(new KeyValuePair<double, State>(s.boundValue / s.path.Count, s));

            maxSize = 0;
            while (!agenda.IsEmpty && stopwatch.ElapsedMilliseconds < 60000 && bssf.costOfRoute() != s.boundValue)
            {
                if (agenda.Count > maxSize) maxSize = agenda.Count;
                State u = agenda.Dequeue().Value;
                if (u.boundValue < bssf.costOfRoute())
                {
                    if (stopwatch.ElapsedMilliseconds % 5000 == 0) updateUI();
                    ArrayList children = generateChildren(u);
                    foreach (State w in children)
                    {
                        if (w.boundValue < bssf.costOfRoute())
                        {
                            if (w.path.Count == Cities.Length)
                            {
                                bssf = bssfFromIntArray(w.path);
                                myBssf = (int[])w.path.ToArray(System.Type.GetType("System.Int32"));
                                while (updateBssf(myBssf)) ;
                                updateUI();
                            }
                            else
                                agenda.Add(new KeyValuePair<double, State>(w.boundValue / w.path.Count, w));
                        }
                    }
                }
            }
            updateUI();
        }