コード例 #1
0
        public VoronoiMap GimmesomeVeoroiois(List <VoronoiPoint> sites)
        {
            eventQ  = new FastPriorityQueue <FastSiteQueueNode>(sites.Count + 1);
            circleQ = new FastPriorityQueue <FastCircleQueueNode>(sites.Count * sites.Count);

            foreach (VoronoiPoint pt in sites)
            {
                var pointasevent = new SiteEvent(pt);
                eventQ.Enqueue(new FastSiteQueueNode(pointasevent), pointasevent.NodePriority);
            }

            while (eventQ.Count != 0)
            {
                if (circleQ.Count != 0 && circleQ.First().point.circleLength <= eventQ.First().point.X)
                {
                    ProcessCircleEvent();
                }
                else
                {
                    ProcessPointEvent();
                }
            }

            while (circleQ.Count != 0)
            {
                ProcessCircleEvent();
            }

            var finalmap = regionsT.FinishEdges();

            return(finalmap);
        }
コード例 #2
0
        public DijkstraGraphDistance(int nMaxNodes, int nMaxID,
                                     IEnumerable <int> nodeIDs,
                                     Func <int, int, float> nodeDistanceF,
                                     Func <int, IEnumerable <int> > neighboursF,
                                     IEnumerable <Vector2d> seeds = null // these are pairs (index, seedval)
                                     )
        {
            int initial_max = (nMaxNodes < 1024) ? nMaxNodes : nMaxNodes / 4;

            Queue = new FastPriorityQueue <GraphNode>(initial_max);

            NodeDistanceF = nodeDistanceF;
            NeighboursF   = neighboursF;

            Nodes = new SparseObjectList <GraphNode>(nMaxID, nMaxNodes);
            Seeds = new List <int>();

            max_value = float.MinValue;

            if (seeds != null)
            {
                foreach (var v in seeds)
                {
                    AddSeed((int)v.x, (float)v.y);
                }
            }
        }
コード例 #3
0
        public override void Execute(State state, FastPriorityQueue <Event> eventQueue)
        {
            // Free the platform
            station.Free(platform);

            // Reset ready for departure
            tram.ResetReadyForDeparture();

            // Claim lane
            SwitchLane lane = Switch.ExitLaneFor(platform);

            System.Diagnostics.Debug.WriteLine($"DepartureStartstation: tram {tram.id}, station: {station.name}, {platform}, {lane}, time: {state.time}");

            // Clear the lane it's leaving over in 60s
            eventQueue.Enqueue(new ClearSwitchLane(station, lane), state.time + Config.c.switchClearanceTime);

            // Queue next arrival
            int stationIndex    = state.stations.IndexOf(station);
            int newStationIndex = stationIndex + 1;

            // Make sure trams do not take over each other
            int drivingTime = Sampling.drivingTime(Config.c.transferTimes[stationIndex].averageTime);
            int arrivalTime = station.SignalNextArrival(state.time + drivingTime);

            eventQueue.Enqueue(new ExpectedTramArrival(tram, newStationIndex), arrivalTime);
        }
コード例 #4
0
        /// <summary>
        /// Load the precomputed pathfinding graph from file.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private bool ReadGraph(string file)
        {
            if (!File.Exists(file))
            {
                return(false);
            }

            try
            {
                Stream          stream    = File.Open(file, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();

                _graphFastMove = (List <PathNode>)formatter.Deserialize(stream);
                stream.Close();

                _openSet = new FastPriorityQueue <PathNode>(_graphFastMove.Count + 1);

                if (SanityCheckGraph())
                {
                    return(true);
                }
                else
                {
                    _graphFastMove = null;
                    _openSet       = null;
                    return(false);
                }
            }
            catch (Exception exception)
            {
                Debug.Log("Error reading graph file: " + exception.Message);
                return(false);
            }
        }
コード例 #5
0
        private static FastPriorityQueue <Node> PopulateQueue2Y(List <Point2Y> points)
        {
            var queue = new FastPriorityQueue <Node>(points.Count);

            Node prev = null;

            for (var i = 0; i < points.Count; i++)
            {
                var area = i == 0 || i == points.Count - 1 ? float.MaxValue : CalcArea2Y(points[i - 1], points[i], points[i + 1]);

                var node = new Node
                {
                    Index = i,
                    Point = points[i],
                    Prev  = prev
                };

                if (prev != null)
                {
                    prev.Next = node;
                }

                prev = node;
                queue.Enqueue(node, area);
            }

            return(queue);
        }
コード例 #6
0
ファイル: AStarGrid.cs プロジェクト: lihaoyang411/MoonShot
        public AStarGrid(byte[,] map, ByteVector2 from, ByteVector2 to)
        {
            // Check params
            if (map[from.Y, from.X] != 0)
            {
                Console.WriteLine("ERROR: Cannot path to full space");
                return;
            }
            if (map[to.Y, to.X] != 0)
            {
                Console.WriteLine("ERROR: Cannot path from full space.");
                return;
            }

            // Initialize grid state
            // Invert destination for 'cavern optimization'
            destination = from;
            byteMap     = map;
            nodeTracker = new TileNode[map.GetLength(0), map.GetLength(0)];
            nodeQueue   = new FastPriorityQueue <TileNode>(map.GetLength(0) * map.GetLength(0));

            // Calculate shortest path
            // Start from destination for 'cavern optimization' -- prevents scanning of larger territories
            AStar(to, from);
        }
コード例 #7
0
ファイル: AStar.cs プロジェクト: jballaban/game1
 public AStar(int maxNodesToExpand = 1000)
 {
     frontier     = new FastPriorityQueue <INode <T>, T>(maxNodesToExpand);
     stateToNode  = new Dictionary <T, INode <T> >();
     explored     = new Dictionary <T, INode <T> >();  // State -> node
     createdNodes = new List <INode <T> >(maxNodesToExpand);
 }
コード例 #8
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);
    }
コード例 #9
0
    protected void AddToFastOpen(Node child, Node parent, FastPriorityQueue <Node> list)
    {
        double newFValue, gValue;

        if (!useThetaStar)
        {
            newFValue = CalculateFValue(child, parent, out gValue);
        }
        else
        {
            newFValue = CalculateFValue(child, parent, out gValue, out parent);
        }

        if (newFValue == Mathf.Infinity)
        {
            return;
        }
        if (!list.Contains(child))                                          //if child is not already in open list
        {
            list.Enqueue(child, (float)newFValue);                          //add to open list
            SetValues(child, parent, gValue);
        }
        else                                                        //child is already in open list
        {
            float oldFValue = child.Priority;
            if (newFValue < oldFValue)                              //if f-value of child in open list is greather than current f-value
            {
                list.UpdatePriority(child, (float)newFValue);
                SetValues(child, parent, gValue);
            }
        }
    }
コード例 #10
0
            public Node(int gIndex, int depth, int x, int y, FastPriorityQueue <Option> unvisited)
            {
                GIndex       = gIndex;
                Erosion      = (gIndex + depth) % 20183;
                Type         = Erosion % 3;
                AllowedTools = new HashSet <Option>();
                if (x == 0 && y == 0)
                {
                    AllowedTools.Add(new Option(x, y, Tool.Torch, Type));
                }
                else if (Type == 0)
                {
                    AllowedTools.Add(new Option(x, y, Tool.Climbing, Type));
                    AllowedTools.Add(new Option(x, y, Tool.Torch, Type));
                }
                else if (Type == 1)
                {
                    AllowedTools.Add(new Option(x, y, Tool.Climbing, Type));
                    AllowedTools.Add(new Option(x, y, Tool.Nothing, Type));
                }
                else
                {
                    AllowedTools.Add(new Option(x, y, Tool.Torch, Type));
                    AllowedTools.Add(new Option(x, y, Tool.Nothing, Type));
                }

                foreach (var tool in AllowedTools)
                {
                    unvisited.Enqueue(tool, tool.Distance);
                }
            }
コード例 #11
0
    static MarchingCubesDispatcher instance; // just used to make sure only one of these at once
    void Awake()
    {
        if (!SystemInfo.supportsComputeShaders)
        {
            Debug.LogError("THIS IS BAD");
            DestroyImmediate(gameObject);
            return;
        }

        if (instance == null)
        {
            instance = this;
        }
        else
        {
            DestroyImmediate(this);
            return;
        }

        queue = new FastPriorityQueue <ChunkRequest>(10000);

        kernelMC = MarchingCubesCS.FindKernel("MarchingCubes");
        //kernelTripleCount = MarchingCubesCS.FindKernel("TripleCount");

        MarchingCubesCS.SetInt("_gridSize", resolution);
        MarchingCubesCS.SetFloat("_isoLevel", 0.0f);    // halfway point for noise in range [-1, 1]

        workers = new MarchingCubesWorker[numWorkers];
        for (int i = 0; i < workers.Length; ++i)
        {
            workers[i] = new MarchingCubesWorker(resolution, kernelMC, MarchingCubesCS, noiseMat);
        }
    }
コード例 #12
0
    public void SolveContinuumCrowdsForTile(CC_Tile tile, List <Location> goal)
    {
        f = tile.f;
        C = tile.C;
        g = tile.g;

        N = f.GetLength(0);
        M = f.GetLength(1);

        if (N == 0 || M == 0)
        {
            Debug.Log("Eikonal Solver initiated with 0-dimension");
        }

        Phi = new float[N, M];

        dPhi     = new Vector2[N, M];
        velocity = new Vector2[N, M];

        accepted  = new bool[N, M];
        this.goal = new bool[N, M];

        considered = new FastPriorityQueue <FastLocation>(N * M);

        neighbor = new FastLocation(0, 0);

        computeContinuumCrowdsFields(goal);
    }
コード例 #13
0
 public static void InitializeThreadStatics()
 {
     distances      = new Dictionary <T, float>();
     queue          = new FastPriorityQueue <KeyValuePair <T, float> >(new DistanceComparer());
     singleNodeList = new List <T>();
     tmpResult      = new List <KeyValuePair <T, float> >();
 }
コード例 #14
0
 public static void Initialize(Grid targetGrid)
 {
     grid = targetGrid;
     openListPriorityQueue = new FastPriorityQueue <Tile>(grid.GridSizeX * grid.GridSizeY);
     finalPath             = new List <Tile>((int)Math.Round(grid.Tiles.Length * 0.1f));
     closeDictionary       = new Dictionary <int, Tile>((int)Math.Round(grid.Tiles.Length * 0.1f));
 }
コード例 #15
0
ファイル: ThreadPool.cs プロジェクト: zawarnoy/lab6spp
        public ThreadPool(string logFilePath, int minThreads, int maxThreads, int cleanupInterval = 200)
        {
            if (logFilePath == null)
            {
                throw new ArgumentNullException(nameof(logFilePath));
            }
            _logger = new FileLogger(logFilePath);
            if (!(_logger as FileLogger).CheckPath())
            {
                throw new ArgumentException("Bad path.");
            }

            if (minThreads < 0)
            {
                throw new ArgumentException("Need more min threads.");
            }

            if (maxThreads < minThreads || maxThreads == 0)
            {
                throw new ArgumentException("Need more max threads.");
            }

            MinThreads       = minThreads;
            MaxThreads       = maxThreads;
            _userTaskQueue   = new FastPriorityQueue <ProrityContainer>(maxThreads);
            _lastTaskCleanup = DateTime.Now;
            _cleanupInterval = cleanupInterval;

            lock (_taskList)
            {
                AddTasks(MinThreads);
            }

            _logger.writeMessage($"Created {MinThreads} threads.");
        }
コード例 #16
0
        public override void Execute(State state, FastPriorityQueue <Event> eventQueue)
        {
            System.Diagnostics.Debug.WriteLine($"ExpectedDepartureStartstation: tram {tram.id}, station: {station.name}, {platform}, Timetable: {timeTableTime}, time: {state.time}");

            // Close doors if it is time to leave
            if (state.time >= timeTableTime)
            {
                // Mark tram as ready for departure
                tram.ReadyForDeparture();

                // Start leaving directly when possible
                SwitchLane lane    = Switch.ExitLaneFor(platform);
                bool       isFirst = station.first == platform;
                if (isFirst && station._switch.SwitchLaneFree(lane))
                {
                    station._switch.UseSwitchLane(lane);
                    eventQueue.Enqueue(new DepartureStartstation(tram, station, platform), state.time);
                }
            }
            // Otherwise let extra passengers enter
            else
            {
                (int pInExtra, List <int> e) = station.BoardPassengers(tram);
                entrances = e;
                int extraTime = Sampling.passengerExchangeTime(0, pInExtra);
                eventQueue.Enqueue(new ExpectedDepartureStartstation(tram, station, platform, timeTableTime), state.time + extraTime);
            }
        }
コード例 #17
0
ファイル: Day22.cs プロジェクト: jenzy/Advent-of-Code
        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);
                }
            }
        }
コード例 #18
0
ファイル: AStar.cs プロジェクト: Chris3606/GoRogue
        // Private constructor that does work of others
#pragma warning disable CS8618 // _heuristic is initialized via Heuristic so ignore erroneous warning
        private AStar(IGridView <bool> walkabilityView, Distance distanceMeasurement,
                      Func <Point, Point, double>?heuristic = null, IGridView <double>?weights = null,
                      double minimumWeight = 1.0)
#pragma warning restore CS8618
        {
            Weights = weights;

            WalkabilityView        = walkabilityView;
            DistanceMeasurement    = distanceMeasurement;
            MinimumWeight          = minimumWeight;
            _cachedMinWeight       = minimumWeight;
            MaxEuclideanMultiplier = MinimumWeight / Point.EuclideanDistanceMagnitude(new Point(0, 0),
                                                                                      new Point(WalkabilityView.Width, WalkabilityView.Height));

            Heuristic = heuristic !; // Handles null and exposes as non-nullable since it will never allow null

            var maxSize = walkabilityView.Width * walkabilityView.Height;

            _nodes        = new AStarNode?[maxSize];
            _closed       = new BitArray(maxSize);
            _cachedWidth  = walkabilityView.Width;
            _cachedHeight = walkabilityView.Height;

            _openNodes = new FastPriorityQueue <AStarNode>(maxSize);
        }
コード例 #19
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);
        }
コード例 #20
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>());
        }
コード例 #21
0
 public static bool Pop(FastPriorityQueue <KeyValuePair <IntVec3, float> > __instance)
 {
     lock (innerList(__instance))
     {
         KeyValuePair <IntVec3, float> result = innerList(__instance)[0];
         int num   = 0;
         int count = innerList(__instance).Count;
         innerList(__instance)[0] = innerList(__instance)[count - 1];
         innerList(__instance).RemoveAt(count - 1);
         count = innerList(__instance).Count;
         for (; ;)
         {
             int num2 = num;
             int num3 = 2 * num + 1;
             int num4 = num3 + 1;
             if (num3 < count && CompareElements(__instance, num, num3) > 0)
             {
                 num = num3;
             }
             if (num4 < count && CompareElements(__instance, num, num4) > 0)
             {
                 num = num4;
             }
             if (num == num2)
             {
                 break;
             }
             SwapElements(__instance, num, num2);
         }
     }
     return(false);
 }
コード例 #22
0
 public WorldVehiclePathfinder(World world) : base(world)
 {
     this.world = world;
     calcGrid   = new PathFinderNodeFast[Find.WorldGrid.TilesCount];
     openList   = new FastPriorityQueue <CostNode>(new CostNodeComparer());
     Instance   = this;
 }
コード例 #23
0
        public override void Execute(State state, FastPriorityQueue <Event> eventQueue)
        {
            // Clear switch (no lane cleared if coming from depot)
            SwitchLane lane = fromDepot ? SwitchLane.None : Switch.ArrivalLaneFor(platform);

            eventQueue.Enqueue(new ClearSwitchLane(station, lane), state.time + Config.c.switchClearanceTime);

            // Log
            System.Diagnostics.Debug.WriteLine($"ArrivalEndstation: tram {tram.id}, station: {station.name}, {platform}, {lane}, time: {state.time}");

            // Check if tram can do another round trip if it is at endstation with depot
            if (!station.TramToDepot(state.time))
            {
                // Board and unboard
                (int pOut, int pIn, List <int> e) = station.UnboardAndBoard(tram, tram.passengerCount);
                entrances = e;

                // Calculate when to schedule departure
                // If boarding/unboarding takes shorter than the turnaround, take the turnaround time
                int passengerTransferTime = state.time + Math.Max(Sampling.passengerExchangeTime(pOut, pIn), Config.c.turnAroundTimeFor(station));
                int nextDepartureTime     = station.NextDeparture();
                int nextEventTime         = Math.Max(passengerTransferTime, nextDepartureTime);

                // Queue event
                eventQueue.Enqueue(new ExpectedDepartureStartstation(tram, station, platform, nextDepartureTime), nextEventTime);
            }
            // Transfer tram to depot
            else
            {
                station.Free(platform);
            }
        }
コード例 #24
0
        void InitPQ()
        {
            uf = VertexNode.MakeUnionFind(heMesh);

            for (int i = 0; i < uf.NumNodes; i++)
            {
                uf[i].Quadric = vertQuadrics[i];
            }

            PQ = new FastPriorityQueue <FaceNode>(heMesh.Faces.Length);

            nodes = new FaceNode[heMesh.Faces.Length];

            for (int i = 0; i < heMesh.Faces.Length; i++)
            {
                Face f = heMesh.Faces[i];
                if (f.IsBoundary)
                {
                    continue;
                }
                nodes[i] = new FaceNode(f);

                Edge  lowestCost = OptimalEdge(f);
                float cost       = Cost(lowestCost);

                PQ.Enqueue(nodes[i], cost);
            }
        }
コード例 #25
0
ファイル: NavUtils.cs プロジェクト: hdmmY/BillionsUnit
    private static void SetOriginOpenListForCanonicalDijkstra(FastPriorityQueue <PathNode> openList,
                                                              MapColliderInfo map, int2 origin, int2 dir)
    {
        int2 next = origin + dir;

        if (MapColliderUtils.UnReachable(map, next.x, next.y))
        {
            return;
        }

        float cost = 1f;

        if (dir.x != 0 && dir.y != 0)
        {
            if (MapColliderUtils.UnReachable(map, origin + new int2(dir.x, 0)) &&
                MapColliderUtils.UnReachable(map, origin + new int2(0, dir.y)))
            {
                return;
            }

            cost = 1.5f;
        }

        map.IntegrationField[next.x, next.y] = cost;
        openList.Enqueue(new PathNode(next, dir), cost);
    }
コード例 #26
0
        public override void Execute(State state, FastPriorityQueue <Event> eventQueue)
        {
            var station = state.stations[stationIndex];

            station.Free();

            // Enqueue current tram
            if (station.HasQueue())
            {
                Tram newOccupant = station.OccupyFromQueue();
                eventQueue.Enqueue(new TramArrival(newOccupant, stationIndex), state.time + Config.c.stationClearanceTime);
            }

            // Schedule arrival at next station
            int newStationIndex = stationIndex + 1 == state.stations.Count ? 0 : stationIndex + 1;
            int drivingTime     = Sampling.drivingTime(Config.c.transferTimes[stationIndex].averageTime);

            Debug.WriteLine($"TramDeparture: tram {tram.id}: {station.name}, dir: {station.direction}, time: {state.time}");

            // Make sure trams do not take over each other
            int arrivalTime = station.SignalNextArrival(state.time + drivingTime);

            if (state.stations[newStationIndex] is Endstation endstation)
            {
                eventQueue.Enqueue(new ExpectedArrivalEndstation(tram, endstation), arrivalTime);
            }
            else
            {
                eventQueue.Enqueue(new ExpectedTramArrival(tram, newStationIndex), arrivalTime);
            }
        }
コード例 #27
0
 private static int CompareElements(FastPriorityQueue <KeyValuePair <int, float> > __instance, int i, int j)
 {
     lock (innerList(__instance))
     {
         return(comparer(__instance).Compare(innerList(__instance)[i], innerList(__instance)[j]));
     }
 }
コード例 #28
0
 public static void Initialize(GridController targetGridController)
 {
     gridController        = targetGridController;
     openListPriorityQueue = new FastPriorityQueue <Tile>(gridController.GridSizeX * gridController.GridSizeY);
     finalPath             = new List <Tile>(Mathf.RoundToInt(gridController.Tiles.Length * 0.1f));
     closeDictionary       = new Dictionary <int, Tile>(Mathf.RoundToInt(gridController.Tiles.Length * 0.1f));
 }
コード例 #29
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);
            }
        }
コード例 #30
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));
        }
コード例 #31
0
ファイル: NavMap.cs プロジェクト: George-Poulos/Traffix
    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);
    }
コード例 #32
0
	// Use this for initialization
	void Start () {
        currentState = BattleState.START;
        battleGenerator = new BattleGenerator();
        this.turnQueue = battleGenerator.generateBattle();
        this.alliedCharacters = battleGenerator.alliedCharacters;
        this.enemies = battleGenerator.enemies;
        currentState = BattleState.START;
        
    }
コード例 #33
0
        public void Awake() {

            entity = GetComponent<Entity>();
            decisions = new List<Decision>();
            scoreQueue = new FastPriorityQueue<ScoreNode>(1000);

            if (packageCreator != null) {
                package = packageCreator.Create();
                decisions.AddRange(package.decisions);
            }

        }
コード例 #34
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.
        }
コード例 #36
0
ファイル: midi.cs プロジェクト: kecosgrove/SimpleMIDI
 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());
     }
 }
コード例 #37
0
 public BattleGenerator()
 {
     pq = new FastPriorityQueue<QueuedEntity>(MAX_NUMBER_ENTITIES);
     alliedCharacters = GameInformation.alliedCharacters;
 }