Пример #1
0
        override protected void EvaluateOutputs()
        {
            if (ShouldOutput())
            {
                outputPorts[0].Value = queue.Dequeue().value;
                EmitEvaluationRequired();
            }
            else
            {
                outputPorts[0].Value = null;
            }

            IConvertible value = InValue(0);

            if (object.ReferenceEquals(value, lastInput) || (!object.ReferenceEquals(value, null) && value.Equals(lastInput)))
            {
                return;
            }
            lastInput = value;
            if (!ValueToBool(value))
            {
                return;
            }
            int        delay      = Math.Max(1, InInt(1));
            int        outputTick = Manager.CurrentTick + delay;
            QueueEntry entry      = new QueueEntry(outputTick, value);

            if (queue.Count >= queue.MaxSize)
            {
                queue.Dequeue();
            }
            queue.Enqueue(entry, outputTick);
        }
Пример #2
0
        static void TestCase4()
        {
            var random = new Random();
            var myHeap = new FibonacciHeap<double>(int.MinValue, Comparer<double>.Default);
            var thirdPartyHeap = new FastPriorityQueue<FastPriorityQueueNode>(1000);

            for (var i = 0; i < 1000; i++)
            {
                if (random.Next(3) == 0 && thirdPartyHeap.Any())
                {
                    var myResult = myHeap.ExtractMin();
                    var otherResult = thirdPartyHeap.Dequeue();
                    Assert(myResult.Item1);
                    Assert(Math.Abs(myResult.Item2 - otherResult.Priority) < double.Epsilon);
                }
                else
                {
                    var value = random.NextDouble()*10;
                    myHeap.Insert(value);
                    thirdPartyHeap.Enqueue(new FastPriorityQueueNode(), value);
                }
            }

            while (thirdPartyHeap.Any())
            {
                var myResult = myHeap.ExtractMin();
                var otherResult = thirdPartyHeap.Dequeue();
                Assert(myResult.Item1);
                Assert(Math.Abs(myResult.Item2 - otherResult.Priority) < double.Epsilon);
            }
        }
Пример #3
0
        /// <summary>
        /// Processes the queue and fires events.
        /// </summary>
        private void QueueProcessing()
        {
            TimeSpan waitForNewTimeOut = TimeSpan.Zero;

            while (!_cancellationToken.IsCancellationRequested)
            {
                lock (_eventsAvailableLock) {
                    // wait until we're flagged that there are events available.
                    Monitor.Wait(_eventsAvailableLock, waitForNewTimeOut > TimeSpan.Zero ? waitForNewTimeOut : Scheduler._defaultProcessWaitTime);

                    // reset time to wait.
                    waitForNewTimeOut = TimeSpan.Zero;

                    lock (_queueLock) {
                        if (_priorityQueue.First == null)
                        {
                            // no more items on the queue, go to wait.
                            Console.WriteLine($"{nameof(Scheduler)}: Queue empty.");
                            continue;
                        }

                        // store a single 'current' time for processing of all items in the queue
                        // TODO: use 'current' time from Game.Instance
                        var currentTimeInMilliseconds = GetMillisecondsAfterReferenceTime(DateTime.Now);

                        // check the current queue and fire any events that are due.
                        while (_priorityQueue.Count > 0)
                        {
                            // the first item always points to the next-in-time event available.
                            var nextEvent = _priorityQueue.First;

                            // check if this event has been cancelled.
                            if (_cancelledEvents.Contains(nextEvent.EventId))
                            {
                                // dequeue, clean and move next.
                                _priorityQueue.Dequeue();
                                CleanAllAttributedTo(nextEvent.EventId, nextEvent.RequestorId);
                                continue;
                            }

                            // check if the event is due
                            if (nextEvent.Priority <= currentTimeInMilliseconds)
                            {
                                // actually dequeue this item.
                                _priorityQueue.Dequeue();

                                OnEventFired?.Invoke(this, new EventFiredEventArgs(nextEvent));
                                continue;
                            }

                            // else the next item is in the future, so figure out how long to wait, update and break.
                            waitForNewTimeOut = TimeSpan.FromMilliseconds(nextEvent.Priority < currentTimeInMilliseconds ? 0 : nextEvent.Priority - currentTimeInMilliseconds);
                            break;
                        }
                    }
                }
            }
        }
Пример #4
0
        public byte GetThresholdLevel()
        {
            // blend together groups of pixels to average their data and get rid of local spikes
            int weightedArraySize = DATA_ARRAY_SIZE - 4;
            uint[] weightedData = new uint[weightedArraySize];
            for (int i = 0; i < weightedArraySize; ++i)
            {
                weightedData[i] =
                    4 * Data[i + 2] +
                    3 * (Data[i + 1] + Data[i + 3]) +
                    Data[i] + Data[i + 4];
            }

            // find highest local maximum (biggest concentration of pixels of a single color
            int queueSize = (int)Math.Ceiling(weightedArraySize / 2f);
            FastPriorityQueue<ThresholdPoint> queue = new FastPriorityQueue<ThresholdPoint>(queueSize);
            for (int i = 1; i < weightedArraySize - 1; ++i)
            {
                // check if current point is higher than both of its neighbors
                if (weightedData[i] > weightedData[i + 1] && weightedData[i] > weightedData[i - 1])
                {
                    queue.Enqueue(new ThresholdPoint(i, weightedData[i]), -weightedData[i]);        // reversing queue priority to store higher values in front
                }
            }

            // find two highest value groups separated by a certain minimal distance
            ThresholdPoint a = queue.Dequeue();
            ThresholdPoint b = queue.Dequeue();
            int minPixelDistance = 16;
            while (Math.Abs(a.Index - b.Index) < minPixelDistance)
            {
                b = queue.Dequeue();
            }

            // switch points around if necessary so that 'a' represents a lower index
            if (a.Index > b.Index)
            {
                ThresholdPoint t = a;
                a = b;
                b = t;
            }

            // find the lowest value between these two groups
            uint minVal = a.Value;
            int minPos = a.Index;

            for (int i = a.Index + 1; i < b.Index; ++i)
            {
                if (weightedData[i] < minVal)
                {
                    minVal = weightedData[i];
                    minPos = i;
                }
            }

            return (byte)(minPos + 2);
        }
Пример #5
0
        /// <summary>
        /// Benchmark
        /// </summary>
        public void EnqueueDequeue()
        {
            Enqueue();

            for (int i = 0; i < QueueSize; i++)
            {
                Queue.Dequeue();
            }
        }
Пример #6
0
    // A* pathfinding on tilemap
    public static List <Vector3> FindPath(Vector2 start, Vector2 end, Tilemap t, bool useDiagonals)
    {
        List <Vector3> ret = new List <Vector3>();
        Dictionary <Vector2, Vector2> cameFrom = new Dictionary <Vector2, Vector2>();
        Dictionary <Vector2, float>   cost     = new Dictionary <Vector2, float>();
        Vector2 current;
        float   newcost = 0;
        float   dist    = 0;
        FastPriorityQueue <QueueNode> queue = new FastPriorityQueue <QueueNode>(64);

        queue.Enqueue(new QueueNode(start), 0);
        cost.Add(start, 0);

        while (queue.Count != 0)
        {
            current = queue.Dequeue().data;

            if (Vector2.SqrMagnitude(end - current) < 0.5f)
            {
                if (!cameFrom.ContainsKey(end) && cameFrom.ContainsKey(current))
                {
                    cameFrom.Add(end, cameFrom[current]);
                }
                break;
            }

            List <Vector3> neighbors;
            if (useDiagonals)
            {
                neighbors = GetTileNeighborDiagonal(t, current);
            }
            else
            {
                neighbors = GetTileNeighbor(t, current);
            }

            foreach (Vector3 neighbor in neighbors)
            {
                newcost = cost[current] + 0.5f;
                if (!cost.ContainsKey(neighbor) || newcost < cost[neighbor])
                {
                    cost[neighbor] = newcost;
                    if (useDiagonals)
                    {
                        dist = Mathf.Max(Mathf.Abs(neighbor.x - end.x), Mathf.Abs(neighbor.y - end.y));
                    }
                    else
                    {
                        dist = Vector2.Distance(neighbor, end);
                    }
                    queue.Enqueue(new QueueNode(neighbor), newcost + dist);
                    cameFrom[neighbor] = current;
                }
            }
        }

        TraverseCameFrom(end, cameFrom, ret);

        return(ret);
    }
Пример #7
0
        private Node <T> BuildGraphAndReturnGoalNode(T startPosition, T goalPosition)
        {
            _frontier = new FastPriorityQueue <Node <T> >(150);
            _graph    = new Node <T> [_maxNumberOfNodes];
            var heuristic = new Func <T, float>(position => _heuristic(position, goalPosition));

            var initial = new Node <T>(startPosition, _indexMap(startPosition));

            _frontier.Enqueue(initial, 0);
            _graph[initial.Index] = initial;

            while (_frontier.Count > 0)
            {
                var current = _frontier.Dequeue();

                if (current.Position.Equals((goalPosition)))
                {
                    return(current);
                }

                AddNeighbours(current, heuristic);

                _debug?.Invoke(_graph);
            }

            return(null);
        }
Пример #8
0
        public override object Part2()
        {
            var map   = Parse();
            var queue = new FastPriorityQueue <QueueNode>(20000);

            queue.Enqueue(new QueueNode((0, 0), Tool.Torch, 0), 0);
            var shortestPath = new Dictionary <(int x, int y, Tool tool), int>();

            while (true)
            {
                var cur = queue.Dequeue();
                if (shortestPath.TryGetValue(cur.Key, out var shortest) && shortest <= cur.Len)
                {
                    continue;
                }
                shortestPath[cur.Key] = cur.Len;
                if (cur.Key == map.Target)
                {
                    return(cur.Len);
                }

                foreach (var t in map.Tools(cur.Coord).Where(x => x != cur.Tool))
                {
                    queue.Enqueue(new QueueNode(cur.Coord, t, cur.Len + 7), cur.Len + 7);
                }

                foreach (var nc in cur.Neighbours().Where(nc => map.Tools(nc).Contains(cur.Tool)))
                {
                    queue.Enqueue(new QueueNode(nc, cur.Tool, cur.Len + 1), cur.Len + 1);
                }
            }
        }
Пример #9
0
    public void AStar(Coord2D from, Coord2D to)
    {
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();

        // Initialize start node
        int      initialHeuristic = EuclideanDistance(from, to);
        TileNode startNode        = new TileNode(from.x, from.y, 0, initialHeuristic);

        // Store start node
        nodeQueue.Enqueue(startNode, startNode.totalCost);
        nodeTracker[startNode.y, startNode.x] = startNode;

        int timeC = 0;

        while (true)
        {
//            timeC++;
//            if (timeC > 14)

//            {
//                yield return null;
//                timeC = 0;
//            }

            if (nodeQueue.Count == 0) // If the queue is empty, exit and fail
            {
                print("UNABLE TO FIND PATH!");
                break;
            }

            TileNode bestNode = nodeQueue.Dequeue();

            transform.position = new Vector3(bestNode.x, bestNode.y, 1);
            GameObject.Instantiate(frontierMarker).transform.position = transform.position;


            // Set closed state and break if dest. reached
            if (SetClosedState(bestNode))
            {
                ShowBestPath(bestNode);
                break;
            }

            AScanAdjacent(bestNode);
        }

        stopWatch.Stop();

        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                           ts.Hours, ts.Minutes, ts.Seconds,
                                           ts.Milliseconds / 10);

        print("RunTime " + elapsedTime);
    }
        public void DijkstraShortestPath(int source, int exitIndex)
        {
            int length = width * height;

            int[] preCopy = new int[length * 4];
            for (int i = 0; i < preCopy.Length; ++i)
            {
                preCopy[i] = -1;
            }
            initVar();
            distance[source] = 0;
            queue.Enqueue(new PathNode(source, distance[source]), distance[source]);
            while (queue.Count != 0)
            {
                PathNode pathNode = queue.Dequeue();
                if (visit[pathNode.point])
                {
                    continue;                 //已计算
                }
                visit[pathNode.point] = true; //k节点已遍历
                for (int m = first[pathNode.point]; m != -1; m = next[m])
                {
                    if (value[m] + distance[pathNode.point] < distance[v[m]])
                    {
                        distance[v[m]] = value[m] + distance[pathNode.point];
                        preCopy[v[m]]  = pathNode.point;
                        queue.Enqueue(new PathNode(v[m], value[v[m]]), value[v[m]]);
                    }
                }
            }
            for (int i = 0; i < preCopy.Length; ++i)
            {
                pre[exitIndex, i] = preCopy[i];
            }
        }
Пример #11
0
 protected virtual T GetLowest()
 {
     return(OpenSet.Dequeue());
     //var lowest = OpenSet[0];
     //for (int i = 1; i < OpenSet.Count; i++) {
     //    if (OpenSet[i].TotalCost < lowest.TotalCost) {
     //        lowest = OpenSet[i];
     //        continue;
     //    }
     //    var totalDiff = Math.Abs(OpenSet[i].TotalCost - lowest.TotalCost);
     //    if (totalDiff > Accuracy) {
     //        continue;
     //    }
     //    var endDiff = Math.Abs(OpenSet[i].EndCost - lowest.EndCost);
     //    if (endDiff > Accuracy) {
     //        if (OpenSet[i].EndCost < lowest.EndCost) {
     //            lowest = OpenSet[i];
     //        }
     //        continue;
     //    }
     //    if (OpenSet[i].GetTravelCost(null, Start, End) < lowest.GetTravelCost(null, Start, End)) {
     //        lowest = OpenSet[i];
     //    }
     //}
     //return lowest;
 }
    /// <summary>
    /// Pops the item with the lowest priority off of the queue.
    /// </summary>
    public T Dequeue()
    {
        WrappedNode popped = _underlyingQueue.Dequeue();

        _mapDataToWrappedNode.Remove(popped.data);
        return(popped.data);
    }
Пример #13
0
    // Hay que resetear la Astar cada vez que se llame, reseatear todo las variables a valor del start
    public List <Vector2> calculatePath(int [,] tablero, Vector2 pathStart, Vector2 pathEnd)
    {
        fillMarked(tablero);
        fillTableroNode(tablero, pathEnd);

        tableroNode [(int)pathStart.x, (int)pathStart.y].g      = 0;
        tableroNode [(int)pathStart.x, (int)pathStart.y].estado = Node.state.open;
        // referencia a un nodo que se va a considerar a continuacion
        Node myNode = tableroNode [(int)pathStart.x, (int)pathStart.y];
        // Nodo que vamos a usar para guardar el nodo final
        Node aux = null;

        open.Enqueue(myNode, myNode.g);
        while (open.Count != 0)
        {
            myNode        = open.Dequeue();
            myNode.estado = Node.state.closed;
            marked [(int)myNode.pos.x, (int)myNode.pos.y] = true;
            aux = addNeighbours(myNode, pathEnd);
            if (aux != null)
            {
                open.Clear();
                return(getPath(aux));
            }
        }
        return(null);
    }
Пример #14
0
    private List <Node> GetSamePrimKeys()
    {
        List <Node> samePrim      = new List <Node>();
        float       firstPriority = fastOpenListPrim.First().Priority;

        while (fastOpenListPrim.Count > 0)
        {
            if (fastOpenListPrim.First().Priority <= firstPriority)
            {
                samePrim.Add(fastOpenListPrim.Dequeue());
            }
            else
            {
                break;
            }
        }
        for (int i = 0; i < samePrim.Count; i++)
        {
            fastOpenListPrim.Enqueue(samePrim[i], samePrim[i].Priority);
        }
        if (fastOpenListPrim.Count == 0)
        {
            Debug.Log("empty open list");
        }
        return(samePrim);
    }
Пример #15
0
        public override IEnumerable <Node> AStar(Node from, Node to)
        {
            var openSet = new FastPriorityQueue <Node>(Width * Height);

            openSet.Enqueue(from, 0f);

            while (openSet.Count > 0)
            {
                var currentNode = openSet.Dequeue();
                if (currentNode == to)
                {
                    var path = ReconstructPath(currentNode);

                    foreach (var node in this)
                    {
                        node.Reset();
                    }

                    return(path);
                }

                currentNode.InClosedSet = true;

                foreach (var neighbor in currentNode.Neighbors)
                {
                    if (neighbor.InClosedSet)
                    {
                        continue;
                    }

                    var tentativeGScore = currentNode.GScore + currentNode.Distance(neighbor);

                    if (openSet.Contains(neighbor) && tentativeGScore >= neighbor.GScore)
                    {
                        continue;
                    }

                    neighbor.CameFrom = currentNode;
                    neighbor.GScore   = tentativeGScore;

                    var fs = tentativeGScore + HeuristicCostEstimate(neighbor, to);

                    if (openSet.Contains(neighbor))
                    {
                        openSet.UpdatePriority(neighbor, fs);
                    }
                    else
                    {
                        openSet.Enqueue(neighbor, fs);
                    }
                }
            }

            foreach (var node in this)
            {
                node.Reset();
            }

            return(new List <Node>());
        }
        bool CollapseNextEdge()
        {
            if (PQ.Count == 0)
            {
                return(false);
            }

            FaceNode nextFace = PQ.Dequeue();

            // If this face is already degenerate from another edge collapse, skip it.
            if (nextFace.face.Collapsed)
            {
                return(true);
            }

            Edge minEdge = OptimalEdge(nextFace.face);
            int  v1      = minEdge.anyHalfEdge.tailVertex.Index;

            CollapseEdge(minEdge);

            // Update priorities around each merged vertex
            foreach (int v in uf.Find(v1).MergedPoints)
            {
                FixPQAroundVertex(heMesh.Vertices[v]);
            }

            return(true);
        }
Пример #17
0
        public List <Vector2Int> FindPath(Vector2Int start, Vector2Int end)
        {
            if (!_grid.CanMove(start) || !_grid.CanMove(end))
            {
                return(null);
            }
            _grid.Clear();
            _start = start;
            _end   = end;
            _openSet.Clear();

            // 后面大括号内为  初始化列表
            var startNode = new Jps_Node(_start)
            {
                Cost = 0, IsOpen = false, IsClose = false, IsForce = false
            };

            _openSet.Enqueue(startNode, startNode.Cost);
            // 每次取 估值函数最小的节点 检测
            while (_openSet.Count > 0)
            {
                Jps_Node cur = _openSet.Dequeue();
                cur.IsClose = true;
                if (cur.Pos == _end)
                {
                    return(Trace(cur));
                }
                IdentitySuccessors(cur);
            }

            return(null);
        }
Пример #18
0
        public void ProcessCircleEvent()
        {
            var p = circleQ.Dequeue().point;

            regionsT.ProcessCircleEvent(p);
            AddCreatedCircleEvents();
        }
Пример #19
0
        private void AStar(ByteVector2 from, ByteVector2 to)
        {
            // Initialize start node
            int initialHeuristic = EuclideanDistance(from, to);

            TileNode startNode = new TileNode(from.X, from.Y, 0, initialHeuristic);

            // Store start node
            nodeQueue.Enqueue(startNode, startNode.TotalCost);
            nodeTracker[startNode.Y, startNode.X] = startNode;

            // Run A*
            while (true)
            {
                if (nodeQueue.Count == 0) // If the queue is empty, exit and fail
                {
                    break;
                }

                // Get the next best node
                TileNode bestNode = nodeQueue.Dequeue();

                // Set closed state and break if dest. reached
                if (SetClosedState(bestNode))
                {
                    SetBestPath(bestNode);
                    break;
                }

                // Scan all adjacent nodes
                AStarScanAdjacent(bestNode);
            }
        }
Пример #20
0
        public Path GetShortestPath(string from, string to)
        {
            if (!_nodes.TryGetValue(from, out var fromNode))
            {
                throw new Exception("from node not exist");
            }
            if (!_nodes.TryGetValue(to, out var toNode))
            {
                throw new Exception("to node not exist");
            }

            var distances = new Dictionary <Node, int>();

            foreach (var node in _nodes.Values)
            {
                distances.Add(node, int.MaxValue);
            }
            distances.Remove(fromNode);
            distances.Add(fromNode, 0);

            var visited = new HashSet <Node>();

            var privouseNode = new Dictionary <Node, Node>();

            var queue = new FastPriorityQueue <NodeEntry>(10);

            queue.Enqueue(node: new NodeEntry(fromNode, 0), priority: 0);

            while (queue.Any())
            {
                var current = queue.Dequeue().GetNode();
                visited.Add(current);

                foreach (var edge in current.GetEdges())
                {
                    var edgeTo = Get(edge.To());
                    if (visited.Contains(edgeTo))
                    {
                        continue;
                    }

                    var newDistance = distances[current] + edge.GetWeight();
                    if (newDistance >= distances[edgeTo])
                    {
                        continue;
                    }

                    distances.Remove(edgeTo);
                    distances.Add(edgeTo, newDistance);
                    if (privouseNode.TryGetValue(edgeTo, out var currentNode))
                    {
                        privouseNode.Remove(edgeTo);
                    }
                    privouseNode.Add(edgeTo, current);
                    queue.Enqueue(new NodeEntry(edgeTo, newDistance), newDistance);
                }
            }
            return(BuildPath(privouseNode, toNode));
        }
Пример #21
0
    private List <NavPath> Dijkstra(Node s)
    {
        Dictionary <long, QueueNode> touched = new Dictionary <long, QueueNode>();
        HashSet <long> done = new HashSet <long>();
        FastPriorityQueue <QueueNode> pq = new FastPriorityQueue <QueueNode>(map.Nodes.Count);
        List <NavPath> ret = Enumerable.Repeat(NavPath.NoPath, intersections.Count).ToList();

        QueueNode start = new QueueNode(s.id);

        start.path    = new NavPath();
        touched[s.id] = start;
        pq.Enqueue(start, 0);

        while (pq.Count != 0)
        {
            QueueNode qn       = pq.Dequeue();
            float     distance = qn.Priority;
            NavPath   p        = qn.path;
            Node      n        = map.Nodes[qn.id];
            done.Add(n.id);
            ret[pathMapping[n.id]] = p;
            foreach (var edgeId in n.Edges)
            {
                Way edge = map.Ways[edgeId];
                if (edge.GetNext(n.id) != -1)
                {
                    Node  next      = map.Nodes[edge.GetNext(n.id)];
                    float newWeight = distance + edge.weight;
                    if (!done.Contains(next.id))
                    {
                        List <Vector3> points = new List <Vector3>(edge.waypoints);
                        if (edge.isBack(n.id))
                        {
                            points.Reverse();
                        }
                        if (touched.ContainsKey(next.id))
                        {
                            qn = touched[next.id];
                            if (qn.Priority > newWeight)
                            {
                                pq.UpdatePriority(qn, newWeight);
                                qn.path = new NavPath(p.getPoints());
                                qn.path.Add(points);
                            }
                        }
                        else
                        {
                            qn      = new QueueNode(next.id);
                            qn.path = new NavPath(p.getPoints());
                            qn.path.Add(points);
                            touched[next.id] = qn;
                            pq.Enqueue(qn, newWeight);
                        }
                    }
                }
            }
        }
        return(ret);
    }
Пример #22
0
        private int GetShortestPathToTarget()
        {
            var visitedPoints    = new Dictionary <Point, HashSet <EquipmentType> >();
            var consideredPoints = new FastPriorityQueue <PointNode>((this._furthestPoint.X + 1) * (this._furthestPoint.Y + 1) * 3);

            consideredPoints.Enqueue(new PointNode
            {
                P         = new Point(0, 0),
                Time      = 0,
                Equipment = EquipmentType.Torch
            }, 0);

            while (consideredPoints.Any())
            {
                var consideredPoint = consideredPoints.Dequeue();

                if (!visitedPoints.ContainsKey(consideredPoint.P))
                {
                    visitedPoints.Add(consideredPoint.P, new HashSet <EquipmentType> {
                        consideredPoint.Equipment
                    });
                }
                else
                {
                    if (visitedPoints[consideredPoint.P].Contains(consideredPoint.Equipment))
                    {
                        continue;
                    }

                    visitedPoints[consideredPoint.P].Add(consideredPoint.Equipment);
                }

                if (consideredPoint.P == this._targetPosition)
                {
                    if (consideredPoint.Equipment == EquipmentType.Torch)
                    {
                        return(consideredPoint.Time);
                    }

                    var nextPoint = new PointNode
                    {
                        P         = consideredPoint.P,
                        Equipment = EquipmentType.Torch,
                        Time      = consideredPoint.Time + 7
                    };

                    consideredPoints.Enqueue(nextPoint, nextPoint.Time);
                }

                var neighbours = this.GetNextPoints(consideredPoint, visitedPoints);

                foreach (var neighbour in neighbours)
                {
                    consideredPoints.Enqueue(neighbour, neighbour.Time);
                }
            }

            return(int.MaxValue);
        }
Пример #23
0
        public void ProcessPointEvent()
        {
            var p            = eventQ.Dequeue().point;
            var pointAsEvent = new SiteEvent(p.basepoint);

            regionsT.AddToBeachLine(pointAsEvent);
            AddCreatedCircleEvents();
        }
        /// <summary>
        ///     Wyszukuje najkrótszą ścieżkę pomiędzy dwoma polami.
        ///     Implementacja algorytmu A*.
        /// </summary>
        /// <param name="fields">Tablica pól z zadeklarowną dostępnością. Muszą dziedziczyć po klasie PathFindableField</param>
        /// <param name="start">Pole startowe</param>
        /// <param name="destination">Pole końcowe</param>
        /// <param name="minIndexLimit">Minimalne indeksy pól branych pod uwagę przy wyznaczaniu ścieżki</param>
        /// <param name="maxIndexLimit">Maksymalne indeksy pól branych pod uwagę przy wyznaczaniu ścieżki</param>
        /// <seealso cref="PathFindableField"/>
        /// <exception cref="ArgumentNullException" />
        /// <exception cref="ArgumentOutOfRangeException" />
        /// <returns>Najkrótsza ścieżka (stos)</returns>
        internal static Stack <Vector2Int> FindPath(bool[][] fields, Vector2Int start, Vector2Int destination, Vector2Int minIndexLimit, Vector2Int maxIndexLimit)
        {
#if DEBUG
            CheckArguments(fields, start, destination, minIndexLimit, maxIndexLimit);
#endif
            var openSet   = new FastPriorityQueue <AStarPosition>((maxIndexLimit.x - minIndexLimit.x) * (maxIndexLimit.y - minIndexLimit.y));
            var startNode = new AStarNode();
            InitializeAstarNodes(fields, out AStarNode[][] nodes);
            InitializeParents(fields, out Vector2Int[][] parents);

            AddToOpenSet(openSet, nodes, startNode, start);

            while (openSet.Count > 0)
            {
                var actualNodePosition = openSet.Dequeue();

                // znaleziono ścieżkę
                if (actualNodePosition.position == destination)
                {
                    return(CombinePath(actualNodePosition.position, start, nodes, parents));
                }

                AddToClosedSet(nodes, actualNodePosition.position);

                foreach (var neighborPosition in GetNeighbors(fields, nodes, actualNodePosition.position, minIndexLimit, maxIndexLimit))
                {
                    if (IsInClosedSet(neighborPosition, nodes))
                    {
                        continue;
                    }

                    var actualG = nodes[actualNodePosition.position.x][actualNodePosition.position.y].g + 1;

                    if (IsInOpenSet(neighborPosition, nodes))
                    {
                        var neighbor = nodes[neighborPosition.x][neighborPosition.y];

                        if (actualG < neighbor.g)
                        {
                            parents[neighborPosition.x][neighborPosition.y] = actualNodePosition.position;
                            neighbor.g = actualG;

                            openSet.UpdatePriority(actualNodePosition, neighbor.F);
                        }
                    }
                    else
                    {
                        parents[neighborPosition.x][neighborPosition.y]     = actualNodePosition.position;
                        nodes[neighborPosition.x][neighborPosition.y].g     = actualG;
                        nodes[neighborPosition.x][neighborPosition.y].h     = HexHelper.GetDistance(neighborPosition, destination);
                        nodes[neighborPosition.x][neighborPosition.y].state = AStarNode.States.InOpenSet;
                        openSet.Enqueue(new AStarPosition(neighborPosition), nodes[neighborPosition.x][neighborPosition.y].F);
                    }
                }
            }

            return(new Stack <Vector2Int>());
        }
Пример #25
0
    void FindPath(Vector3 a_StartPos, Vector3 a_TargetPos)
    {
        Node StartNode  = nodeMesh.NodeFromWorldPoint(a_StartPos);  //Gets the node closest to the starting position
        Node TargetNode = nodeMesh.NodeFromWorldPoint(a_TargetPos); //Gets the node closest to the target position

        if (StartNode != null && TargetNode != null)
        {
            FastPriorityQueue <Node> OpenList = new FastPriorityQueue <Node>(200);
            //SimplePriorityQueue<Node> OpenList = new FastPriorityQueue<Node>(maxN_Calculations);//List of nodes for the open list
            HashSet <Node> ClosedList = new HashSet <Node>(); //Hashset of nodes for the closed list

            OpenList.Enqueue(StartNode, StartNode.FCost);     //Add the starting node to the open list to begin the program
            while (OpenList.Count > 0)                        //Whilst there is something in the open list
            {
                Node CurrentNode = OpenList.Dequeue();        //Create a node and set it to the first item in the open list
                OpenList.ResetNode(CurrentNode);
                //OpenList.Remove(CurrentNode);//Remove that from the open list
                ClosedList.Add(CurrentNode);             //And add it to the closed list

                if (CurrentNode == TargetNode)           //If the current node is the same as the target node
                {
                    GetFinalPath(StartNode, TargetNode); //Calculate the final path
                }
                //Debug.Log("el nodo en cuestion tiene x vecinos" + CurrentNode.NeighbNodes.Count);
                Node[] nNodes = nodeMesh.GetNeighbNodes(CurrentNode);
                for (int i = 0; i < nNodes.Length; i++)
                {
                    Node NeighborNode = nNodes[i];
                    if (NeighborNode == null)
                    {
                        continue;
                    }
                    if (NeighborNode.BIsWall || ClosedList.Contains(NeighborNode))
                    {
                        continue;                                                                        //If the neighbor is a wall or has already been checked // Skip it
                    }
                    int MoveCost = CurrentNode.IgCost + GetManhattenDistance(CurrentNode, NeighborNode); //Get the F cost of that neighbor

                    if (MoveCost < NeighborNode.IgCost || !OpenList.Contains(NeighborNode))              //If the f cost is greater than the g cost or it is not in the open list
                    {
                        NeighborNode.IgCost      = MoveCost;                                             //Set the g cost to the f cost
                        NeighborNode.IhCost      = GetManhattenDistance(NeighborNode, TargetNode);       //Set the h cost
                        NeighborNode.ParentNode1 = CurrentNode;                                          //Set the parent of the node for retracing steps

                        if (!OpenList.Contains(NeighborNode))                                            //If the neighbor is not in the openlist
                        {
                            //Add it to the list
                            OpenList.Enqueue(NeighborNode, NeighborNode.FCost);
                        }
                    }
                }
            }
            //while (OpenList.Count > 0)
            //{
            //    OpenList.ResetNode(OpenList.Dequeue());
            //}
        }
    }
Пример #26
0
            private static int FindShortestPathTime(int[,] erosionLevelMap, int x, int y, int equip, int time)
            {
                var queue = new FastPriorityQueue <State>(100000);
                var set   = new HashSet <(int, int, int)>();

                queue.Enqueue(new State(x, y, equip), time);

                while (true)
                {
                    var state = queue.Dequeue();

                    time  = (int)state.Priority;
                    x     = state.X;
                    y     = state.Y;
                    equip = state.Equip;

                    if (x == TARGET_X &&
                        y == TARGET_Y &&
                        equip == TORCH)
                    {
                        return(time);
                    }

                    if (set.Contains((x, y, equip)))
                    {
                        continue;
                    }

                    set.Add((x, y, equip));

                    for (int newEquip = 0; newEquip < 3; newEquip++)
                    {
                        if (CorrectEquipForRegionType(newEquip, GetRegionType(erosionLevelMap[x, y])))
                        {
                            queue.Enqueue(new State(x, y, newEquip), (time + 7));
                        }
                    }

                    for (int direction = 0; direction < 4; direction++)
                    {
                        int dx, dy;
                        (dx, dy) = GetDirectionVector(direction);

                        if (x + dx >= DIMENSION_X ||
                            x + dx < 0 ||
                            y + dy >= DIMENSION_Y ||
                            y + dy < 0)
                        {
                            continue;
                        }

                        if (CorrectEquipForRegionType(equip, GetRegionType(erosionLevelMap[x + dx, y + dy])))
                        {
                            queue.Enqueue(new State(x + dx, y + dy, equip), (time + 1));
                        }
                    }
                }
            }
    public override bool Find(DirectionGraph graph, Node start, Node end)
    {
        priorityQueue = new FastPriorityQueue <Node>(graph.VerticeCount());
        searchSteps   = new Queue <Node>();

        System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        costForStartToTarget        = new Dictionary <Node, int>();
        costForStartToTarget[start] = 0;

        priorityQueue.Enqueue(start, 0);
        while (priorityQueue.Count > 0)
        {
            Node min = priorityQueue.Dequeue();
            if (min == end)
            {
                watch.Stop();
                executionTimes = watch.Elapsed.TotalMilliseconds;
                CalculateCostAndGeneratePath(start, end, graph);
                return(true);
            }
            List <DirectionEdge> minNeighbors = graph.GetNeighborEdge(min);
            int costForStartToMin             = costForStartToTarget[min];
            for (int i = 0, count = minNeighbors.Count; i < count; i++)
            {
                Node neighbor = minNeighbors[i].to;
                int  costForStartToNeighbor = int.MaxValue;
                if (costForStartToTarget.ContainsKey(neighbor))
                {
                    costForStartToNeighbor = costForStartToTarget[neighbor];
                }
                int newCostSoFar = costForStartToMin + minNeighbors[i].weight;
                if (newCostSoFar < costForStartToNeighbor)
                {
                    costForStartToTarget[neighbor] = newCostSoFar;
                    nodesComeFrom[neighbor]        = min;
                    if (priorityQueue.Contains(neighbor))
                    {
                        priorityQueue.UpdatePriority(neighbor, newCostSoFar);
                    }
                    else
                    {
                        priorityQueue.Enqueue(neighbor, newCostSoFar);
                    }
                }
            }
            if (min != start)
            {
                searchSteps.Enqueue(min);
            }
        }
        watch.Stop();
        executionTimes = watch.Elapsed.TotalMilliseconds;
        searchSteps.Clear();
        return(false);
    }
Пример #28
0
 public static void GetNextReminder()
 {
     if (reminderQueue != null && reminderQueue.Count != 0)
     {
         Console.WriteLine("MEMORY QUEUE IS NOT EMPTY");
         reminderHolder = reminderQueue.Dequeue();
         Console.WriteLine(reminderQueue.Count);
     }
 }
Пример #29
0
            public Node NextOpen()
            {
                Node node = open.Dequeue();

                opened[node.pos.x, node.pos.y] = null;
                closed[node.pos.x, node.pos.y] = true;

                return(node);
            }
Пример #30
0
        private static State Solve(Problem problem, out int totalScore)
        {
            int timeLeft = problem.DayCount;

            totalScore = 0;
            var state        = new State();
            var bookIDsAdded = new HashSet <int>();

            var libraryQueue           = new FastPriorityQueue <Library>(problem.Libraries.Length);
            var idsOfLibrariesToSignUp = new HashSet <int>();

            foreach (var library in problem.Libraries)
            {
                float score = GetPotentialScore(problem, library, bookIDsAdded, timeLeft);
                if (score > 0)
                {
                    libraryQueue.Enqueue(library, -score);
                    idsOfLibrariesToSignUp.Add(library.ID);
                }
            }

            while (libraryQueue.Count != 0)
            {
                var library = libraryQueue.Dequeue();
                idsOfLibrariesToSignUp.Remove(library.ID);

                if (library.SignUpTime < timeLeft)
                {
                    var signUp = new SignUp
                    {
                        LibraryID = library.ID,
                    };
                    AddBooks(problem, signUp, timeLeft, bookIDsAdded, out int scoreForLibrary);
                    if (scoreForLibrary > 0)
                    {
                        state.SignUps.Add(signUp);
                        timeLeft   -= library.SignUpTime;
                        totalScore += scoreForLibrary;

                        foreach (var libraryToSignUp in idsOfLibrariesToSignUp.Select(id => problem.Libraries[id]).ToArray())
                        {
                            float score = GetPotentialScore(problem, libraryToSignUp, bookIDsAdded, timeLeft);
                            if (score == 0)
                            {
                                libraryQueue.Remove(libraryToSignUp);
                                idsOfLibrariesToSignUp.Remove(libraryToSignUp.ID);
                            }
                            else
                            {
                                libraryQueue.UpdatePriority(libraryToSignUp, -score);
                            }
                        }
                    }
                }
            }
            return(state);
        }
Пример #31
0
        public void TestIntQueuePriority()
        {
            FastPriorityQueue <Node> fastQueue = new FastPriorityQueue <Node>(100);

            for (int i = 1; i < 50; i++)
            {
                fastQueue.Enqueue(new Node(), i * 2);
            }
            Node n = new Node();

            n.Name = "Test";
            fastQueue.Enqueue(n, 2.0f);
            fastQueue.Enqueue(new Node(), -1.0f);
            Assert.IsTrue(fastQueue.First.Priority == -1.0f);
            Assert.IsFalse(fastQueue.First.Name == "Test");
            fastQueue.Dequeue();
            fastQueue.Dequeue();
            Assert.IsTrue(fastQueue.First.Name == "Test");
        }
Пример #32
0
        static void TestCase2()
        {
            var random = new Random();
            var myHeap = new BinomialHeap<double>(double.MinValue, Comparer<double>.Default);
            var otherQueue = new FastPriorityQueue<FastPriorityQueueNode>(10000);
            for (var i = 0; i < 10000; i++)
            {
                if (otherQueue.Any() && random.Next(3) == 0)
                {
                    Assert(Math.Abs(myHeap.ExtractMin().Item2 - otherQueue.Dequeue().Priority) < double.Epsilon);
                }
                else
                {
                    var newValue = random.NextDouble()*10;
                    myHeap.Insert(newValue);
                    otherQueue.Enqueue(new FastPriorityQueueNode(), newValue);
                }
            }

            while(otherQueue.Any())
                Assert(Math.Abs(myHeap.ExtractMin().Item2 - otherQueue.Dequeue().Priority) < double.Epsilon);
        }
        public static void RunExample()
        {
            //First, we create the priority queue.  We'll specify a max of 10 users in the queue
            FastPriorityQueue<User> priorityQueue = new FastPriorityQueue<User>(MAX_USERS_IN_QUEUE);

            //Next, we'll create 5 users to enqueue
            User user1 = new User("1 - Jason");
            User user2 = new User("2 - Tyler");
            User user3 = new User("3 - Valerie");
            User user4 = new User("4 - Joseph");
            User user42 = new User("4 - Ryan");

            //Now, let's add them all to the queue (in some arbitrary order)!
            priorityQueue.Enqueue(user4, 4);
            priorityQueue.Enqueue(user2, 0); //Note: Priority = 0 right now!
            priorityQueue.Enqueue(user1, 1);
            priorityQueue.Enqueue(user42, 4);
            priorityQueue.Enqueue(user3, 3);

            //Change user2's priority to 2.  Since user2 is already in the priority queue, we call UpdatePriority() to do this
            priorityQueue.UpdatePriority(user2, 2);

            //Finally, we'll dequeue all the users and print out their names
            while(priorityQueue.Count != 0)
            {
                User nextUser = priorityQueue.Dequeue();
                Console.WriteLine(nextUser.Name);
            }

            //Output:
            //1 - Jason
            //2 - Tyler
            //3 - Valerie
            //4 - Joseph
            //4 - Ryan

            //Notice that when two users with the same priority were enqueued, they were dequeued in the same order that they were enqueued.
        }
Пример #34
0
 public void WriteMIDI(string path)
 {
     HashSet<Note>.Enumerator enumerator = notes.GetEnumerator();
     FastPriorityQueue<Note> startQueue = new FastPriorityQueue<Note>(numNotes);
     FastPriorityQueue<Note> endQueue = new FastPriorityQueue<Note>(numNotes);
     while (enumerator.MoveNext())
     {
         startQueue.Enqueue(enumerator.Current, enumerator.Current.Priority);
     }
     using (BinaryWriter writer = new BinaryWriter(File.Open(path+trackName + ".mid", FileMode.Create)))
     {
         writer.Write(OneTrackHeader());
         writer.Write(StandardTrackHeader());
         long deltaStart = 0;
         do
         {
             if (endQueue.Peek() == null)
             {
                 Note note = startQueue.Dequeue();
                 writer.Write(note.MidiStart(deltaStart));
                 deltaStart = (long) note.Priority;
                 endQueue.Enqueue(note, note.Priority+note.GetDuration());
             } else if (startQueue.Peek() == null)
             {
                 Note note = endQueue.Dequeue();
                 writer.Write(note.MidiEnd(deltaStart));
                 deltaStart = (long) note.Priority;
             } else
             {
                 if (endQueue.Peek().Priority > startQueue.Peek().Priority)
                 {
                     Note note = startQueue.Dequeue();
                     writer.Write(note.MidiStart(deltaStart));
                     deltaStart = (long)note.Priority;
                     endQueue.Enqueue(note, note.Priority+note.GetDuration());
                 } else
                 {
                     Note note = endQueue.Dequeue();
                     writer.Write(note.MidiEnd(deltaStart));
                     deltaStart = (long)note.Priority;
                 }
             }
         } while (startQueue.Count + endQueue.Count > 0);
         writer.Write(TrackEnd());
     }
 }