Exemplo n.º 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));
        }
Exemplo n.º 2
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);
    }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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);
        }
        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);
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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;
        }
Exemplo n.º 9
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());
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
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();
                        //}
                    }
                }
            }
        }
        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);
        }
Exemplo n.º 13
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);
        }