コード例 #1
0
        public Queue <MapObject> GetPath(MapObject start, MapObject end)
        {
            ShortestPathResult result = graph.Dijkstra(GetNode(start), GetNode(end)); //result contains the shortest path
            var path = result.GetPath().Select(node => nodePlanetMap[node]);

            return(new Queue <MapObject>(path));
        }
コード例 #2
0
        public static ShortestPathResult DijkstraShortestPath(this Graph graph, Guid start, Guid end)
        {
            if (graph == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query the Dijkstra shortest path from a null graph.");
                return(null);
            }

            m_NonSpatialGraph = graph;

            SetFragments(graph);

            DijkstraSearch(graph, start, end);

            List <Guid> shortestPath = new List <Guid>();

            shortestPath.Add(end);

            double           length    = 0;
            double           cost      = 0;
            List <IRelation> relations = new List <IRelation>();

            DijkstraResult(shortestPath, end, ref length, ref cost, ref relations);
            shortestPath.Reverse();
            List <IBHoMObject> objPath = new List <IBHoMObject>();

            shortestPath.ForEach(g => objPath.Add(graph.Entities[g]));

            List <IBHoMObject> entitiesVisited = m_Fragments.Where(kvp => kvp.Value.Visited).Select(kvp => graph.Entities[kvp.Key]).ToList();
            ShortestPathResult result          = new ShortestPathResult(graph.BHoM_Guid, "DijkstraShortestPath", -1, objPath, length, cost, entitiesVisited, relations);

            return(result);
        }
コード例 #3
0
        public async Task <ShortestPathResult> FindShortestPath(IResortObject @from, IResortObject to)
        {
            await EnsureInitialized();

            var result = new ShortestPathResult
            {
                From = from,
                To   = to
            };
コード例 #4
0
    public override uint?NextHop(uint?source, uint?destination)
    {
        ShortestPathResult result = graph.Dijkstra(NodeToNodeIDMapping[source], NodeToNodeIDMapping[destination]);

        IEnumerable <uint> path = result.GetPath();
        uint?nextHop            = NodeToNodeIDMapping.ToList().Find((x) => x.Value == path.ElementAt(1)).Key;

        return(nextHop);
    }
コード例 #5
0
        public List <City> GetCityPath(ShortestPathResult result)
        {
            List <City> cities = new List <City>();

            foreach (var node in result.GetPath())
            {
                cities.Add(Graph[node].Item);
            }
            return(cities);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: lurongkai/SuperNet
 private static void PrintResult(ShortestPathResult result)
 {
     foreach (var pr in result) {
         Console.WriteLine("--------------------------------------------");
         Console.WriteLine("Target: {0}", pr.Target);
         PrintEdgeTrack(pr.EdgeTracks);
         PrintVertexTrack(pr.VertexTracks);
         Console.WriteLine("--------------------------------------------");
     }
 }
コード例 #7
0
        public static string ToStringPath(this ShortestPathResult pathResult)
        {
            if (!pathResult.IsPathFound)
            {
                return(string.Empty);
            }

            var result = string.Join("-", pathResult.Path.Select(x => x.Name));

            return(result);
        }
コード例 #8
0
        public SearchResultDTO ClickCalculate(Parcel parcel, City source, City destination)
        {
            List <Edge> edges;
            List <City> cities;

            cities = MappingService.GetCities();
            edges  = MappingService.GetEdges(cities);    //context.GetAllEdges();

            Graph <City, string> graphPrice     = GraphFabric.CreateGraphPrice(cities, edges, "priceCost", parcel);
            Graph <City, string> graphTime      = GraphFabric.CreateGraphTime(cities, edges, "timeCost");
            Graph <City, string> graphPriceTime = GraphFabric.CreateGraphTime(cities, edges, "price times cost");

            RouteCalculatorService routeCalcPrice = new RouteCalculatorService(graphPrice);
            ShortestPathResult     resultPrice    = routeCalcPrice.CalculateShortestPath(source, destination);
            List <City>            pathPrice      = routeCalcPrice.GetCityPath(resultPrice);

            RouteCalculatorService routeCalcTime = new RouteCalculatorService(graphTime);
            ShortestPathResult     resultTime    = routeCalcPrice.CalculateShortestPath(source, destination);
            List <City>            pathTime      = routeCalcTime.GetCityPath(resultTime);

            RouteCalculatorService routePriceTime  = new RouteCalculatorService(graphPriceTime);
            ShortestPathResult     resultPriceTime = routeCalcPrice.CalculateShortestPath(source, destination);
            List <City>            pathPriceTime   = routeCalcTime.GetCityPath(resultPriceTime);

            this.SaveParcel(parcel);

            var cPath = new PathDTO()
            {
                Cities   = ReturnCityDtos(pathPrice),
                Duration = 42,
                Price    = resultPrice.Distance
            };

            var fPath = new PathDTO()
            {
                Cities   = ReturnCityDtos(pathTime),
                Duration = resultTime.Distance,
                Price    = 42
            };

            var bPath = new PathDTO()
            {
                Cities   = ReturnCityDtos(pathPriceTime),
                Duration = resultPriceTime.Distance,
                Price    = 42
            };

            return(new SearchResultDTO
            {
                Cheapest = cPath,
                Fastest = fPath,
                Best = bPath
            });
        }
コード例 #9
0
 private static void PrintResult(ShortestPathResult result)
 {
     foreach (var pr in result)
     {
         Console.WriteLine("--------------------------------------------");
         Console.WriteLine("Target: {0}", pr.Target);
         PrintEdgeTrack(pr.EdgeTracks);
         PrintVertexTrack(pr.VertexTracks);
         Console.WriteLine("--------------------------------------------");
     }
 }
コード例 #10
0
        /// <summary>
        /// Calculates closest distance between customer, depot and drone.
        /// </summary>
        /// <param name="customerAddress">Address of a customer</param>
        /// <returns>DeliveryPlan, which contains routes and estimated time.</returns>
        public async Task <DeliveryPlan> Calculate(string customerAddress)
        {
            DeliveryPlan plan     = new DeliveryPlan();
            Location     customer = new Location();

            customer = await _locationService.Find(customerAddress);

            plan.Customer = customer;
            IList <ShortestPathResult>    pathResults = new List <ShortestPathResult>();
            Dictionary <uint, DroneDepot> DepotMap    = new Dictionary <uint, DroneDepot>();
            Dictionary <uint, Store>      StoreMap    = new Dictionary <uint, Store>();

            // Creating graph to be able to use Dijkstra algorithm to find the shortest path.
            var  graph      = new Graph <string, string>();
            uint customerId = graph.AddNode("Customer");

            foreach (DroneDepot depot in Depots)
            {
                uint depotId = graph.AddNode(depot.Name);
                DepotMap.Add(depotId, depot);
                foreach (Store store in _stores)
                {
                    uint storeId = graph.AddNode(store.Name);
                    StoreMap.Add(storeId, store);

                    // converting KM to M, because the cost variable is int, so the accuracy will be in meters.
                    graph.Connect(depotId, storeId, (int)(depot.Coordinate.Distance(store.Coordinate) * 1000), $"{depot.Name} -> {store.Name}");
                    graph.Connect(storeId, customerId, (int)(store.Coordinate.Distance(customer.Coordinate) * 1000), $"{store.Name} -> Customer");
                }
                pathResults.Add(graph.Dijkstra(depotId, customerId));
            }

            // Find the shortest path from path results. Depot -> Store -> Customer
            ShortestPathResult shortestPath = pathResults[0];

            for (int i = 1; i < pathResults.Count; i++)
            {
                shortestPath = pathResults[i].Distance < shortestPath.Distance ? pathResults[i] : shortestPath;
            }

            // Get chosen shortest distance units.
            IList <uint> nodeList = shortestPath.GetPath().ToList();

            plan.Depot = DepotMap.Where(x => x.Key == nodeList[0]).Select(x => x.Value).SingleOrDefault();
            plan.Store = StoreMap.Where(x => x.Key == nodeList[1]).Select(x => x.Value).SingleOrDefault();

            // Calculate delivery time.
            double hours = shortestPath.Distance / DRONESPEED;

            plan.TotalDeliveryTime = TimeSpan.FromSeconds(hours);

            return(plan);
        }
コード例 #11
0
ファイル: AStarShortestPath.cs プロジェクト: BHoM/BHoM_Engine
        public static ShortestPathResult AStarShortestPath(this Graph graph, Guid start, Guid end)
        {
            if (graph == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query the AStar shortest path from a null graph.");
                return(null);
            }

            m_GeometricGraph = graph.IProjectGraph(new GeometricProjection());

            if (m_GeometricGraph.Entities.Count == 0 || m_GeometricGraph.Relations.Count == 0)
            {
                Reflection.Compute.RecordWarning("The graph provided does not contain sufficient spatial entities or relations.\n" +
                                                 "To use a star shortest path provide a graph where some entities implement IElement0D and spatial relations are defined between them.\n" +
                                                 "Shortest path is computed using Dijkstra shortest path instead.");

                return(DijkstraShortestPath(graph, start, end));
            }

            SetFragments(m_GeometricGraph);

            //calculate straight line distance from each entity to the end
            IElement0D endEntity = m_GeometricGraph.Entities[end] as IElement0D;

            foreach (Guid entity in m_GeometricGraph.Entities.Keys.ToList())
            {
                IElement0D element0D = m_GeometricGraph.Entities[entity] as IElement0D;
                m_Fragments[entity].StraightLineDistanceToTarget = element0D.IGeometry().Distance(endEntity.IGeometry());
            }

            AStarSearch(m_GeometricGraph, start, ref end);

            List <Guid> shortestPath = new List <Guid>();

            shortestPath.Add(end);

            double           length    = 0;
            double           cost      = 0;
            List <ICurve>    curves    = new List <ICurve>();
            List <IRelation> relations = new List <IRelation>();

            AStarResult(shortestPath, end, ref length, ref cost, ref curves, ref relations);
            shortestPath.Reverse();

            List <IBHoMObject> objPath = new List <IBHoMObject>();

            shortestPath.ForEach(g => objPath.Add(m_GeometricGraph.Entities[g]));

            List <IBHoMObject> entitiesVisited = m_Fragments.Where(kvp => kvp.Value.Visited).Select(kvp => m_GeometricGraph.Entities[kvp.Key]).ToList();
            ShortestPathResult result          = new ShortestPathResult(graph.BHoM_Guid, "AStarShortestPath", -1, objPath, length, cost, entitiesVisited, relations, curves);

            return(result);
        }
コード例 #12
0
        private Point[] dijkstrasAlgorithm(Map map)
        {
            var graph = new Graph <Point, string>();

            addTilesToGraph(graph, map);
            connectTilesFromGraph(graph, map);
            //oneseign: 41 67
            //Split: 42 48
            //splitting: 12 44
            ShortestPathResult result = graph.Dijkstra(12, 44);
            var path   = result.GetPath();
            var enumer = path.GetEnumerator();
            var points = getPointsFromPath(enumer, map);

            return(points);
        }
コード例 #13
0
        public Tuple <List <int>, int> ComputeRoute(Package packageInfo, TransportCenter from, TransportCenter to)
        {
            var keyFrom = Dictio.centerIdToKey[from.Id];
            var keyTo   = Dictio.centerIdToKey[to.Id];
            ShortestPathResult result = _map.Dijkstra(keyFrom, keyTo);

            List <int> shortestRoute = new List <int>();

            foreach (var node in result.GetPath())
            {
                var centerId = Dictio.keyToCenterId[node];
                shortestRoute.Add(centerId);
            }

            Tuple <List <int>, int> output = new Tuple <List <int>, int>(shortestRoute, result.Distance);

            return(output);
        }
コード例 #14
0
        public BeregnetRute ShortestPath(List <Forbindelse> forbindelser, List <By> byer, Forsendelse forsendelse, string priority)
        {
            var graph = new Graph <int, string>();

            foreach (By by in byer)
            {
                graph.AddNode(by.Id);
            }

            var priorityVar = 0;

            foreach (Forbindelse forbindelse in forbindelser)
            {
                if (priority is "tid")
                {
                    priorityVar = forbindelse.Tid;
                }
                else if (priority is "pris")
                {
                    priorityVar = (int)forbindelse.Pris;
                }
                else if (priority is "blandet")
                {
                    priorityVar = (int)(0.5 * forbindelse.Tid) + (int)(0.5 * forbindelse.Pris);
                }
                graph.Connect((uint)forbindelse.Fra.Id, (uint)forbindelse.Til.Id, priorityVar, "");
            }
            ShortestPathResult result = graph.Dijkstra((uint)forsendelse.Fra.Id, (uint)forsendelse.Til.Id); //result contains the shortest path

            var path = result.GetPath().ToList();
            var minForbindelseList = new List <Forbindelse>();

            for (int i = 0; i < path.Count() - 1; i++)
            {
                var matchingForbindelser = forbindelser.Where(f => f.Fra.Id == path[i] && f.Til.Id == path[i + 1]);
                var minForbindelse       =
                    matchingForbindelser.FirstOrDefault(m => m.Tid == matchingForbindelser.Select(x => x.Tid).Min());
                minForbindelseList.Add(minForbindelse);
            }

            var beregnetRute = CreateBeregnetRute(minForbindelseList, forsendelse);

            return(beregnetRute);
        }
コード例 #15
0
        public void TestMethod1()
        {
            var graph = new Graph <int, string>();

            graph.AddNode(1);
            graph.AddNode(2);
            graph.AddNode(3);
            graph.AddNode(4);

            graph.Connect(1, 2, 5, "");
            graph.Connect(2, 3, 2, "");
            graph.Connect(3, 4, 4, "");
            graph.Connect(2, 4, 5, "");


            ShortestPathResult result = graph.Dijkstra(1, 4); //result contains the shortest path

            List <uint> path = result.GetPath().ToList();

            int i = 3 + 3;
        }
コード例 #16
0
        int[] FindRoutes(
            List <Location> locations,
            List <Route> routes,
            string departureCode,
            string destinationCode)
        {
            var departureLocation   = locations.First(x => x.Code == departureCode);
            var destinationLocation = locations.First(x => x.Code == destinationCode);
            Dictionary <int, uint> locationMapping = new Dictionary <int, uint>();

            var graph = new Graph <int, string>();

            uint index = 1;

            foreach (var location in locations)
            {
                locationMapping.Add(location.Id, index);
                graph.AddNode((int)index);
                index++;
            }

            foreach (var route in routes)
            {
                graph.Connect(
                    locationMapping[route.DepartureLocationId],
                    locationMapping[route.DestinationLocationId],
                    8,
                    string.Empty);
            }

            ShortestPathResult result = graph.Dijkstra(
                locationMapping[departureLocation.Id],
                locationMapping[destinationLocation.Id]); //result contains the shortest path

            var path = result.GetPath();

            return(path.Select(x => locationMapping.First(lm => lm.Value == x).Key).ToArray());
        }
コード例 #17
0
        public static int Answer(int numOfServers, int targetServer, int[,] connectionTimeMatrix)
        {
            // Initialise new Graph
            var graph = new Graph <int, string>();

            for (int i = 0; i < numOfServers; i++)
            {
                graph.AddNode(i);
            }

            // Populate Graph With Adjacency Matrix
            for (int i = 0; i < numOfServers; i++)
            {
                for (uint j = 0; j < numOfServers; j++)
                {
                    graph.Connect(Convert.ToUInt32(i), j, connectionTimeMatrix[i, j], "n/a");
                }
            }

            // Calculate shortest route
            ShortestPathResult result = graph.Dijkstra(0, Convert.ToUInt32(targetServer)); //result contains the shortest path

            return(result.Distance);
        }
コード例 #18
0
        private SampleGraph()
        {
            NodeA = new Node {
                Name = "A"
            };
            NodeB = new Node {
                Name = "B"
            };
            NodeC = new Node {
                Name = "C"
            };
            NodeD = new Node {
                Name = "D"
            };
            NodeE = new Node {
                Name = "E"
            };
            NodeF = new Node {
                Name = "F"
            };
            NodeG = new Node {
                Name = "G"
            };
            InvalidNode = new Node {
                Name = ""
            };

            EdgeAB = new Edge {
                Source = NodeA, Destination = NodeB, Weight = 1
            };
            EdgeAC = new Edge {
                Source = NodeA, Destination = NodeC, Weight = 2
            };
            EdgeBC = new Edge {
                Source = NodeB, Destination = NodeC, Weight = 1
            };
            EdgeBE = new Edge {
                Source = NodeB, Destination = NodeE, Weight = 2
            };
            EdgeBD = new Edge {
                Source = NodeB, Destination = NodeD, Weight = 3
            };
            EdgeCD = new Edge {
                Source = NodeC, Destination = NodeD, Weight = 1
            };
            EdgeCE = new Edge {
                Source = NodeC, Destination = NodeE, Weight = 2
            };
            EdgeDE = new Edge {
                Source = NodeD, Destination = NodeE, Weight = 4
            };
            EdgeDF = new Edge {
                Source = NodeD, Destination = NodeF, Weight = 3
            };
            EdgeEF = new Edge {
                Source = NodeE, Destination = NodeF, Weight = 3
            };
            InvalidEdge = new Edge {
                Source = NodeA, Destination = NodeB, Weight = -1
            };
            Graph = new Graph();

            Graph.AddNode(NodeA);
            Graph.AddNode(NodeB);
            Graph.AddNode(NodeC);
            Graph.AddNode(NodeD);
            Graph.AddNode(NodeE);
            Graph.AddNode(NodeF);
            Graph.AddNode(NodeG);

            Graph.AddEdge(EdgeAB);
            Graph.AddEdge(EdgeAC);
            Graph.AddEdge(EdgeBC);
            Graph.AddEdge(EdgeBE);
            Graph.AddEdge(EdgeBD);
            Graph.AddEdge(EdgeCD);
            Graph.AddEdge(EdgeCE);
            Graph.AddEdge(EdgeDE);
            Graph.AddEdge(EdgeDF);
            Graph.AddEdge(EdgeEF);

            ShortestPathResultA = new ShortestPathResult
            {
                Graph           = Graph,
                Start           = NodeA,
                DistanceToNodes = new Dictionary <Node, int>
                {
                    { NodeA, 0 },
                    { NodeB, 1 },
                    { NodeC, 2 },
                    { NodeD, 3 },
                    { NodeE, 3 },
                    { NodeF, 6 },
                    { NodeG, int.MaxValue }
                },
                PreviousNode = new Dictionary <Node, Node>
                {
                    { NodeA, null },
                    { NodeB, NodeA },
                    { NodeC, NodeA },
                    { NodeD, NodeC },
                    { NodeE, NodeB },
                    { NodeF, NodeD },
                    { NodeG, null }
                }
            };

            ShortestPathResultG = new ShortestPathResult
            {
                Graph           = Graph,
                Start           = NodeG,
                DistanceToNodes = new Dictionary <Node, int>
                {
                    { NodeA, int.MaxValue },
                    { NodeB, int.MaxValue },
                    { NodeC, int.MaxValue },
                    { NodeD, int.MaxValue },
                    { NodeE, int.MaxValue },
                    { NodeF, int.MaxValue },
                    { NodeG, 0 }
                },
                PreviousNode = new Dictionary <Node, Node>
                {
                    { NodeA, null },
                    { NodeB, null },
                    { NodeC, null },
                    { NodeD, null },
                    { NodeE, null },
                    { NodeF, null },
                    { NodeG, null }
                }
            };
        }
コード例 #19
0
        public int Solve()
        {
            var  matrix = BuildMatrix(_depth, _targetX, _targetY);
            uint height = (uint)matrix.GetLength(0);
            uint width  = (uint)matrix.GetLength(1);
            var  graph  = new Graph <(int, int, int), string>();


            for (var lev = 0; lev < 3; ++lev)
            {
                for (var i = 0; i < matrix.GetLength(0); ++i)
                {
                    for (var j = 0; j < matrix.GetLength(1); ++j)
                    {
                        graph.AddNode((i, j, lev));
                    }
                }
            }

            // [0, 1, 2] == [Torch, Any, Climb]

            for (var lev = 0; lev < 3; ++lev)
            {
                for (var i = 0; i < matrix.GetLength(0); ++i)
                {
                    for (var j = 0; j < matrix.GetLength(1); ++j)
                    {
                        // Connect with 7:
                        // Rocky: climb <-> torch = (0, 2)
                        // Wet: any <-> climb = (1, 2)
                        // Narrow: any <-> torch = (0, 1)
                        switch (matrix[i, j])
                        {
                        case Region.Rocky:
                            if (lev == 2)
                            {
                                graph.Connect(ExtractCoords(i, j, 2, height, width),
                                              ExtractCoords(i, j, 0, height, width), 7, "");
                            }
                            else if (lev == 0)
                            {
                                graph.Connect(ExtractCoords(i, j, 0, height, width),
                                              ExtractCoords(i, j, 2, height, width), 7, "");
                            }
                            break;

                        case Region.Wet:
                            if (lev == 2)
                            {
                                graph.Connect(ExtractCoords(i, j, 1, height, width),
                                              ExtractCoords(i, j, 2, height, width), 7, "");
                            }
                            else if (lev == 1)
                            {
                                graph.Connect(ExtractCoords(i, j, 2, height, width),
                                              ExtractCoords(i, j, 1, height, width), 7, "");
                            }
                            break;

                        default:
                            if (lev == 1)
                            {
                                graph.Connect(ExtractCoords(i, j, 1, height, width),
                                              ExtractCoords(i, j, 0, height, width), 7, "");
                            }
                            else if (lev == 0)
                            {
                                graph.Connect(ExtractCoords(i, j, 0, height, width),
                                              ExtractCoords(i, j, 1, height, width), 7, "");
                            }
                            break;
                        }

                        // Connect with 1:
                        // - Torch: narrow <-> rocky   = (0, 2)
                        // - Any:   wet <-> narrow     = (1, 2)
                        // - Climb: rocky <-> wet      = (0, 1)
                        foreach ((int I, int J) in ValidAdjacents(i, j, height, width))
                        {
                            var mio   = (int)matrix[i, j];
                            var tuyo  = (int)matrix[I, J];
                            var ambos = new HashSet <int> {
                                mio, tuyo
                            };

                            if (mio == tuyo)
                            {
                                graph.Connect(ExtractCoords(i, j, lev, height, width),
                                              ExtractCoords(I, J, lev, height, width), 1, "");
                            }

                            switch (lev)
                            {
                            // Torch
                            case 0:
                                if (ambos.SetEquals(new HashSet <int> {
                                    0, 2
                                }))
                                {
                                    graph.Connect(ExtractCoords(i, j, lev, height, width),
                                                  ExtractCoords(I, J, lev, height, width), 1, "");
                                }
                                break;

                            // Any
                            case 1:
                                if (ambos.SetEquals(new HashSet <int> {
                                    1, 2
                                }))
                                {
                                    graph.Connect(ExtractCoords(i, j, lev, height, width),
                                                  ExtractCoords(I, J, lev, height, width), 1, "");
                                }
                                break;

                            // Climb
                            default:
                                if (ambos.SetEquals(new HashSet <int> {
                                    0, 1
                                }))
                                {
                                    graph.Connect(ExtractCoords(i, j, lev, height, width),
                                                  ExtractCoords(I, J, lev, height, width), 1, "");
                                }
                                break;
                            }
                        }
                    }
                }
            }

            ShortestPathResult result = graph.Dijkstra(
                ExtractCoords(0, 0, 0, height, width),
                ExtractCoords(10, 10, 0, height, width));


            foreach (var k in result.GetPath())
            {
                Console.WriteLine(Transform((int)k, (int)height, (int)width));
            }

            Console.WriteLine(result.Distance);

            return(0);
        }
コード例 #20
0
        public ShortestPathResult CalculateShortestPath(City source, City destination)
        {
            ShortestPathResult result = Graph.Dijkstra((uint)source.ID, (uint)destination.ID);

            return(result);
        }
コード例 #21
0
        public async Task <ShortestPathResponse> GetShortestPath(List <int> roomId)
        {
            Graph <int, string> graph = CreateGraph();


            Dictionary <uint, bool> arriveList = new Dictionary <uint, bool>();


            //lấy thằng điểm bắt đầu của map đang hiện hành
            Position startPosition = await _unitOfWork.Repository <Position>().GetAll().
                                     Where(p => p.DescriptionEng == "Start point" &&
                                           p.FloorId == p.Floor.Id &&
                                           p.Floor.MapId == p.Floor.Map.Id &&
                                           p.Floor.Map.Status == true).FirstOrDefaultAsync();

            if (startPosition != null)
            {
                arriveList.Add((uint)startPosition.Id, false);
            }

            //arriveList.Add(1, false);


            //duyệt trong list room đc nhập vào để quét table Position trong databse lấy ra node tương ứng với room, điêu kiện roomid bằng vs id truyền vào và type phải là true (true == node)
            List <int> inputPositions = new List <int>();

            if (roomId.Count() == 1)
            {
                var position = _unitOfWork.Repository <Position>().GetAll().Where(p => p.RoomId == roomId.ElementAt(0)).FirstOrDefault();
                if (position != null)
                {
                    inputPositions.Add((int)position.Id);
                }
            }

            else
            {
                foreach (int id in roomId)
                {
                    var position = _unitOfWork.Repository <Position>().GetAll().Where(p => p.RoomId == id).FirstOrDefault();
                    if (position != null)
                    {
                        inputPositions.Add((int)position.Id);
                    }
                }
            }



            foreach (int node in inputPositions)
            {
                arriveList.Add((uint)node, false);
            }


            ShortestPathResponse shortestPath = new ShortestPathResponse()
            {
                StartNode = 0,
                Distance  = int.MaxValue,
                Path      = new List <uint>()
            };

            uint startNode;

            //vòng for đầu tiên để đổi các start node theo vòng
            foreach (var node in arriveList.Keys.ToList())
            {
                Debug.WriteLine("Start from node {0}:", node);
                startNode = node;
                List <uint> result = new List <uint> {
                    node
                };

                foreach (var key in arriveList.Keys.ToList())
                {
                    arriveList[key] = false;
                }
                //lúc hết 1 vòng for thì status list auto = false hết các phần tử, trừ start node
                arriveList[startNode] = true;

                int totalDistance = 0;

                // Lặp cho đến khi không còn must visit node nào chưa đi qua
                while (arriveList.Values.Any(x => x == false))
                {
                    //chỗ này để t tính total distance của 1 node bắt đầu để so sánh
                    //int count = 0;
                    int  minDistance = int.MaxValue;
                    uint nextNode    = 0;
                    ShortestPathResult pathResult = new ShortestPathResult();

                    //để tính min graph các node tiếp theo
                    foreach (var key in arriveList.Keys.ToList())
                    {
                        var tmp      = graph.Dijkstra(startNode, key);
                        int distance = tmp.Distance;
                        // tính khoảng cách

                        if (distance < minDistance && arriveList[key] == false)
                        // nếu thỏa mãn bé hơn và không lặp node, chưa đi qua thì với vô if này
                        {
                            minDistance = distance;
                            nextNode    = key;
                            pathResult  = tmp;
                        }
                    }


                    totalDistance += minDistance;
                    result.AddRange(pathResult.GetPath().Where(x => x != startNode));
                    //cộng dồn distance để tính tổng của mỗi start node
                    startNode = nextNode;
                    // t gán điểm tiếp theo của start node là cái node vừa đi qua
                    arriveList[nextNode] = true;
                }

                var p = graph.Dijkstra(startNode, node);
                totalDistance += p.Distance;
                result.AddRange(p.GetPath().Where(x => x != startNode));
                result.RemoveAt(result.Count - 1);
                while (true)
                {
                    if (result[0] == 1)
                    {
                        break;
                    }
                    result.Add(result[0]);
                    result.RemoveAt(0);
                }
                result.Add(result[0]);

                if (totalDistance < shortestPath.Distance)
                {
                    shortestPath = new ShortestPathResponse()
                    {
                        StartNode = (int)node,
                        Distance  = totalDistance,
                        Path      = result
                    };
                }
            }
            return(shortestPath);
        }
コード例 #22
0
        static void Main(string[] args)
        {
            TokenResult response;

            while (true)
            {
                try
                {
                    response = client.Post(new AuthLogin {
                        Login = "******", Password = "******"
                    });
                    break;
                }
                catch (Exception)
                {
                }
            }

            client.BearerToken = response.Token;
            visual.BearerToken = response.Token;

            math         = client.Get(new HelpMath());
            optimalSpeed = (math.MaxDuneSpeed + math.MinCanyonSpeed) / 2;
            Deltas       = math.LocationDeltas.ToDictionary(i => i.Direction, i => i.Delta);
            var sessionInfo = client.Post(new Play {
                Map = The_MazeMap
            });

            //var sessionInfo = client.Get(new GetSession {SessionId = $"Bots{RiftMap}" });

            SessionId   = sessionInfo.SessionId;
            CurrentMap  = new Map(sessionInfo.NeighbourCells, sessionInfo.Radius);
            Heading     = sessionInfo.CurrentDirection;
            CurrentCell = CurrentMap.GetCell(sessionInfo.CurrentLocation);
            TargetCell  = CurrentMap.GetCell(sessionInfo.Finish);

            while (Status != PlayerStatusEnum.HappyAsInsane && Status != PlayerStatusEnum.Punished)
            {
                var heading = Heading;
                var @from   = invertedDictionary[CurrentCell.Item1.vector3];
                var to      = invertedDictionary[TargetCell.Item1.vector3];
                ShortestPathResult result = graph.Dijkstra(@from, to); //result contains the shortest path

                var fullpath = result.GetPath();
                var path     = fullpath.Skip(1).FirstOrDefault();
                var cell     = invertedDictionary.FirstOrDefault(pair => pair.Value == path).Key;
                if (cell != null)
                {
                    var delta = cell - CurrentCell.Item1.vector3;
                    var direc = Deltas.FirstOrDefault(pair =>
                                                      pair.Value.Dx == delta.X && pair.Value.Dy == delta.Y && pair.Value.Dz == delta.Z);
                    heading = direc.Key;
                }

                //bool driftWarning = false;
                //int driftDown = 0;

                while (true)
                {
                    int accel   = 0;
                    var nexCell = CurrentMap.GetCell(CurrentCell.Item1, heading);


                    var isTurn = TurnSolution(nexCell, ref heading, ref accel);

                    if (isTurn)
                    {
                        var angle = Math.Abs((int)heading - (int)Heading);
                        if (CurrentSpeed > 0 && angle == 180)
                        {
                            accel = -30;
                        }
                        //foreach (var driftsAngle in math.DriftsAngles)
                        //{
                        //    if (driftsAngle.Angle>=angle && driftsAngle.MaxSpeed>=CurrentSpeed)
                        //    {
                        //        driftDown = CurrentSpeed - driftsAngle.MaxSpeed;
                        //        driftWarning = true;
                        //        heading = heading.TurnLeft();
                        //    }
                        //}

                        //if (!driftWarning)
                        //{
                        //    heading = heading.TurnLeft();
                        //}
                        //else
                        {
                            //nexCell = CurrentMap.GetCell(CurrentCell.Item1, heading);
                            Turn(heading, accel);
                        }
                        break;
                    }
                    else
                    {
                        //if (!GoneCells.ContainsKey(nexCell.Item1.vector3))
                        {
                            heading = heading.TurnLeft();
                        }
                        //else
                        //{
                        //    heading = heading.TurnRight();
                        //}
                    }
                }
            }
        }
コード例 #23
0
ファイル: RoutesController.cs プロジェクト: Ladekarl/Gazelle
        private async Task <Route> GetRouteFromPath(ShortestPathResult result, ICollection <Connection> connections, string deliveryTypes, bool isTime, int weight, int length, int height, int depth)
        {
            var resultConnections = new List <Connection>();
            var path = result.GetPath();

            for (int i = 1; i < path.Count(); i++)
            {
                var firstElement   = path.ElementAt(i - 1);
                var secondElement  = path.ElementAt(i);
                var edgeConnection = connections
                                     .Where(c => c.StartCity.CityId == firstElement && c.EndCity.CityId == secondElement && c.Company == "Telstar")
                                     .OrderBy(c => c.Price)
                                     .FirstOrDefault();

                if (edgeConnection != null)
                {
                    resultConnections.Add(edgeConnection);
                }
            }

            bool hasWar = resultConnections.Any(c => c.EndCity.Country.Conflict || c.StartCity.Country.Conflict);

            var calcPrice = resultConnections.Where(c => c.Price.HasValue).Sum(c => c.Price.Value);
            var calcTime  = resultConnections.Where(c => c.Time.HasValue).Sum(c => c.Time.Value);

            var sentTypes = new List <DeliveryType>();

            if (deliveryTypes != null)
            {
                var deliveryTypesArray = deliveryTypes.Split(',');

                foreach (var deliveryType in deliveryTypesArray)
                {
                    if (!string.IsNullOrEmpty(deliveryType))
                    {
                        var dbType = _context.DeliveryTypes.First(x => x.Name == deliveryType);
                        sentTypes.Add(dbType);
                    }
                }
            }

            if (hasWar)
            {
                var warDelivery = _context.DeliveryTypes.First(x => x.Name == "war");
                if (!sentTypes.Contains(warDelivery))
                {
                    sentTypes.Add(warDelivery);
                }
            }

            var totalPriceAddition = sentTypes.Sum(x => x.Price);

            var route = new Route
            {
                Price       = !isTime ? result.Distance : calcPrice + (calcPrice * (totalPriceAddition / 100)),
                Time        = isTime ? result.Distance : calcTime,
                Companies   = "Telstar",
                Connections = resultConnections
            };

            _context.Routes.Add(route);
            await _context.SaveChangesAsync();

            return(route);
        }