public void TestDecPriority()
        {
            PairingHeap <Plane, int> queue = new PairingHeap <Plane, int>();
            int idCounter = 0;

            Plane plane1 = new Plane();

            plane1.SetInternationalID("id" + idCounter);
            idCounter++;
            plane1.SetPriority(4);
            queue.Add(plane1);

            Plane plane2 = new Plane();

            plane2.SetInternationalID("id" + idCounter);
            idCounter++;
            plane2.SetPriority(5);
            queue.Add(plane2);

            Plane plane3 = new Plane();

            plane3.SetInternationalID("id" + idCounter);
            idCounter++;
            plane3.SetPriority(7);
            queue.Add(plane3);

            queue.ChangePriority(plane2, 89);


            File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\testDecPriority.txt",
                              queue.TraverseLevelOrder());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the minimum-weight path to a goal using the A* algorithm.
        /// </summary>
        /// <remarks>Because the heuristic is not known to be consistent, we cannot use the closed set optimization.</remarks>
        /// <typeparam name="TNode">The type of a node.</typeparam>
        /// <typeparam name="TKey">The type of a node key.</typeparam>
        /// <param name="sources">The set of nodes from which to start the search, weighted by their initial cost.</param>
        /// <param name="key">The function which maps a node to its key.</param>
        /// <param name="next">The function which maps a node to its adjacent nodes.</param>
        /// <param name="goal">The goal predicate.</param>
        /// <param name="heuristic">The possibly-inconsistent heuristic function.</param>
        /// <returns>The minimum-weight path, or null if none exists.</returns>
        private static IWeighted <IEnumerable <TNode> > AStarInconsistent <TNode, TKey>(
            IEnumerable <IWeighted <TNode> > sources,
            Func <TNode, TKey> key,
            Func <TNode, IEnumerable <IWeighted <TNode> > > next,
            Func <TNode, bool> goal,
            Func <TNode, double> heuristic)
        {
            var came_from = new Dictionary <TKey, TNode>();
            IPriorityQueue <double, AStarOpen <TNode> > open_queue = new PairingHeap <double, AStarOpen <TNode> >();
            var open_lookup = new Dictionary <TKey, IPriorityQueueHandle <double, AStarOpen <TNode> > >();

            foreach (var source in sources)
            {
                var u      = source.Value;
                var key_u  = key(u);
                var g_u    = source.Weight;
                var f_u    = g_u + heuristic(u);
                var open_u = new AStarOpen <TNode>(u, g_u);
                open_u.Handle = open_queue.Add(f_u, open_u);
                open_lookup.Add(key_u, open_u.Handle);
            }
            while (open_queue.Count > 0)
            {
                var handle_u = open_queue.Min;
                var u        = handle_u.Value.Node;
                var key_u    = key(u);
                if (goal(u))
                {
                    var path = ReconstructPath(key, came_from, u);
                    return(new Weighted <IEnumerable <TNode> >(path, handle_u.Value.G));
                }
                open_queue.Remove(handle_u);
                open_lookup.Remove(key_u);
                foreach (var uv in next(u))
                {
                    var v     = uv.Value;
                    var key_v = key(v);
                    var g_v   = handle_u.Value.G + uv.Weight;
                    var f_v   = g_v + heuristic(v);
                    IPriorityQueueHandle <double, AStarOpen <TNode> > handle_v;
                    if (open_lookup.TryGetValue(key_v, out handle_v))
                    {
                        if (f_v < handle_v.Key)
                        {
                            open_queue.UpdateKey(handle_v, f_v);
                            handle_v.Value.G = g_v;
                            came_from[key_v] = u;
                        }
                    }
                    else
                    {
                        var open_v = new AStarOpen <TNode>(v, g_v);
                        open_v.Handle = open_queue.Add(f_v, open_v);
                        open_lookup.Add(key_v, open_v.Handle);
                        came_from[key_v] = u;
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the minimum-weight path to a goal using uniform cost search.
        /// </summary>
        /// <typeparam name="TNode">The type of a node.</typeparam>
        /// <typeparam name="TKey">The type of a node key.</typeparam>
        /// <param name="sources">The set of nodes from which to start the search, weighted by their initial cost.</param>
        /// <param name="key">The function which maps a node to its key.</param>
        /// <param name="next">The function which maps a node to its adjacent nodes.</param>
        /// <param name="goal">The goal predicate.</param>
        /// <returns>The minimum-weight path, or null if none exists.</returns>
        public static IWeighted <IEnumerable <TNode> > UniformCostSearch <TNode, TKey>(
            this IEnumerable <IWeighted <TNode> > sources,
            Func <TNode, TKey> key,
            Func <TNode, IEnumerable <IWeighted <TNode> > > next,
            Func <TNode, bool> goal)
        {
            var came_from   = new Dictionary <TKey, TNode>();
            var open_lookup = new Dictionary <TKey, IPriorityQueueHandle <double, TNode> >();
            IPriorityQueue <double, TNode> open_queue = new PairingHeap <double, TNode>();
            var closed = new HashSet <TKey>();

            foreach (var source in sources)
            {
                var u   = source.Value;
                var g_u = source.Weight;
                open_lookup.Add(key(u), open_queue.Add(g_u, u));
            }
            while (open_queue.Count > 0)
            {
                var handle_u = open_queue.Min;
                var u        = handle_u.Value;
                var key_u    = key(u);
                var g_u      = handle_u.Key;
                if (goal(u))
                {
                    var path = ReconstructPath(key, came_from, u);
                    return(new Weighted <IEnumerable <TNode> >(path, g_u));
                }
                open_lookup.Remove(key_u);
                open_queue.Remove(handle_u);
                closed.Add(key_u);
                foreach (var uv in next(u))
                {
                    var v     = uv.Value;
                    var key_v = key(v);
                    if (closed.Contains(key_v))
                    {
                        continue;
                    }
                    IPriorityQueueHandle <double, TNode> v_handle;
                    var g_uv = g_u + uv.Weight;
                    if (open_lookup.TryGetValue(key_v, out v_handle))
                    {
                        if (g_uv < v_handle.Key)
                        {
                            open_queue.UpdateKey(v_handle, g_uv);
                            came_from[key_v] = u;
                        }
                    }
                    else
                    {
                        open_lookup.Add(key_v, open_queue.Add(g_uv, v));
                        came_from[key_v] = u;
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 4
0
        public void return_correct_min_element_and_keep_it_in_heap_on_findmin_operation()
        {
            _heap.Add(9);
            _heap.Add(7);
            _heap.Add(5);
            _heap.Add(3);

            Assert.That(_heap.FindMin(), Is.EqualTo(3));
            Assert.That(_heap.Count, Is.EqualTo(4));
        }
Ejemplo n.º 5
0
        public void StartMessage(OutstandingMessage message, DateTime expires)
        {
            var found = _outstandingRequests.ContainsKey(message.EventId);

            _outstandingRequests[message.EventId] = message;
            if (!found)
            {
                _bySequences.Add(message.ResolvedEvent.OriginalEventNumber, message.ResolvedEvent.OriginalEventNumber);
                _byTime.Add(new RetryableMessage(message.EventId, expires));
            }
        }
Ejemplo n.º 6
0
        public void Handle(AuthenticatedHttpRequestMessage message)
        {
            var manager = message.Manager;
            var match   = message.Match;

            try {
                var reqParams = match.RequestHandler(manager, match.TemplateMatch);
                if (!reqParams.IsDone)
                {
                    _pending.Add(Tuple.Create(DateTime.UtcNow + reqParams.Timeout, manager));
                }
            } catch (Exception exc) {
                Log.Error(exc, "Error while handling HTTP request '{url}'.", manager.HttpEntity.Request.Url);
                InternalServerError(manager);
            }

            PurgeTimedOutRequests();
        }
Ejemplo n.º 7
0
        private void FindPaths()
        {
            var frontier = new PairingHeap <double, Location>(new DoubleComparer())
            {
                { 0, HeroLocation }
            };

            CategorizeObject(ObjectMap[HeroLocation]);

            while (frontier.Count != 0)
            {
                var current = frontier.Pop().Value;
                for (var d = Direction.Up; d <= Direction.RightDown; d++)
                {
                    var next = current.NeighborAt(d);
                    if (IsEnemySpawn(next) ||
                        !ObjectMap.ContainsKey(next))
                    {
                        continue;
                    }
                    var mapObject = ObjectMap[next];
                    CategorizeObject(mapObject);
                    var nextTime = TravelTimes[current] + 0.5 * movementCost[mapObject.Terrain];
                    if (TravelTimes.ContainsKey(next) && !(nextTime < TravelTimes[next]))
                    {
                        continue;
                    }
                    TravelTimes[next] = nextTime;
                    if (IsPassable(mapObject))
                    {
                        frontier.Add(nextTime, next);
                    }
                    previousLocation[next] = current;
                }
            }
        }
        private void ProcessRequest(HttpService httpService, HttpEntity httpEntity)
        {
            var request = httpEntity.Request;

            try {
                var allMatches = httpService.GetAllUriMatches(request.Url);
                if (allMatches.Count == 0)
                {
                    NotFound(httpEntity);
                    return;
                }

                var allowedMethods = GetAllowedMethods(allMatches);

                if (request.HttpMethod.Equals(HttpMethod.Options, StringComparison.OrdinalIgnoreCase))
                {
                    RespondWithOptions(httpEntity, allowedMethods);
                    return;
                }

                var match = allMatches.LastOrDefault(
                    m => m.ControllerAction.HttpMethod.Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase));
                if (match == null)
                {
                    MethodNotAllowed(httpEntity, allowedMethods);
                    return;
                }

                ICodec requestCodec           = null;
                var    supportedRequestCodecs = match.ControllerAction.SupportedRequestCodecs;
                if (supportedRequestCodecs != null && supportedRequestCodecs.Length > 0)
                {
                    requestCodec = SelectRequestCodec(request.HttpMethod, request.ContentType, supportedRequestCodecs);
                    if (requestCodec == null)
                    {
                        BadContentType(httpEntity, "Invalid or missing Content-Type");
                        return;
                    }
                }

                ICodec responseCodec = SelectResponseCodec(request.QueryString,
                                                           request.AcceptTypes,
                                                           match.ControllerAction.SupportedResponseCodecs,
                                                           match.ControllerAction.DefaultResponseCodec);
                if (responseCodec == null)
                {
                    BadCodec(httpEntity, "Requested URI is not available in requested format");
                    return;
                }


                try {
                    var manager =
                        httpEntity.CreateManager(requestCodec, responseCodec, allowedMethods, satisfied => { });
                    var reqParams = match.RequestHandler(manager);
                    if (!reqParams.IsDone)
                    {
                        _pending.Add(Tuple.Create(DateTime.UtcNow + reqParams.Timeout, manager));
                    }
                } catch (Exception exc) {
                    Log.ErrorException(exc, "Error while handling HTTP request '{url}'.", request.Url);
                    InternalServerError(httpEntity);
                }
            } catch (Exception exc) {
                Log.ErrorException(exc, "Unhandled exception while processing HTTP request at [{listenPrefixes}].",
                                   string.Join(", ", httpService.ListenPrefixes));
                InternalServerError(httpEntity);
            }

            PurgeTimedOutRequests();
        }
        public void TestAllOperationsOnRandomNumbers()
        {
            int                      count = 10000; //MIN IS 100
            int                      idCounter = 1;
            List <Plane>             planes = new List <Plane>(count);
            List <Plane>             removed = new List <Plane>(count);
            PairingHeap <Plane, int> queue = new PairingHeap <Plane, int>();
            Random                   random = new Random();
            int                      addCount = 0, succAddCount = 0,
                                     changePriorityCount = 0, succChangePriorityCount = 0,
                                     deleteCount = 0, succDeleteCount = 0,
                                     compareCheck = 0;
            String history                        = "";
            int    deleteFileNumber = 1;


            for (int i = 0; i < count; i++)
            {
                int number = random.Next(0, 100 * count);
                if (number % 5 == 0 || number % 5 == 3 || number % 5 == 4)
                {
                    addCount++;
                    Plane newPlane = new Plane();
                    newPlane.SetInternationalID("id" + idCounter);
                    idCounter++;
                    newPlane.SetPriority(random.Next(11));
                    if (queue.Add(newPlane))
                    {
                        succAddCount++;
                        history += "ADDED: " + newPlane.GetInternationalID() + " with priority " + newPlane.GetPriority() + "\r\n";
                        history += "ROOT: " + queue.Root.Data.GetInternationalID() + " with priority "
                                   + queue.Root.Data.GetPriority() + "\r\n";
                        planes.Add(newPlane);
                    }
                }

                else
                if (number % 5 == 1 || number % 5 == 2)
                {
                    deleteCount++;
                    if (planes.Count > 0)
                    {
                        Plane toDelete = queue.DeleteMin();
                        if (toDelete != null)
                        {
                            history += "" + toDelete.GetInternationalID() + "\r\n";
                            succDeleteCount++;
                            planes.Remove(toDelete);
                            removed.Add(toDelete);
                            history += "DELETED: " + toDelete.GetInternationalID() + " with priority " + toDelete.GetPriority() + "\r\n";
                            if (queue.Root != null)
                            {
                                history += "ROOT: " + queue.Root.Data.GetInternationalID() + " with priority "
                                           + queue.Root.Data.GetPriority() + "\r\n";
                            }
                            else
                            {
                                history += "EMPTY HEAP\r\n";
                            }
                        }
                    }
                    if (removed.Count > 0)
                    {
                        Plane errorneousPlane = queue.Delete(removed[random.Next(0, removed.Count)]);  // SHOULD DO NOTHING
                        if (errorneousPlane != null)
                        {
                            history += "???DELETED: " + errorneousPlane.GetInternationalID()
                                       + " with priority " + errorneousPlane.GetPriority() + "\r\n";
                            if (queue.Root != null)
                            {
                                history += "ROOT: " + queue.Root.Data.GetInternationalID() + " with priority "
                                           + queue.Root.Data.GetPriority() + "\r\n";
                            }
                            else
                            {
                                history += "EMPTY HEAP\r\n";
                            }
                        }
                    }
                }
                if (count >= 100 && number % 100 == 0)
                {
                    changePriorityCount++;

                    if (planes.Count > 0)
                    {
                        int newPriority = random.Next(11);
                        int randomIndex = random.Next(0, planes.Count);
                        if (newPriority != planes[randomIndex].GetPriority())
                        {
                            Assert.IsTrue(queue.ChangePriority(planes[randomIndex],
                                                               newPriority));
                            planes[randomIndex].SetPriority(newPriority);
                            succChangePriorityCount++;
                        }
                    }

                    if (removed.Count > 0)
                    {
                        int newPriority = random.Next(11);
                        int randomIndex = random.Next(0, removed.Count);
                        if (newPriority != removed[randomIndex].GetPriority())
                        {
                            Assert.IsFalse(queue.ChangePriority(removed[randomIndex],
                                                                newPriority));
                        }
                    }

                    if (planes.Count > 0)
                    {
                        int randomIndex = random.Next(0, planes.Count);


                        Plane randomDelete = queue.Delete(planes[randomIndex]);

                        if (randomDelete != null)
                        {
                            planes.RemoveAt(randomIndex);
                            removed.Add(randomDelete);
                        }
                        deleteFileNumber++;
                    }



                    compareCheck++;
                    File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\pairingheapTestHistory.txt",
                                      history);
                    foreach (Plane plane in planes)
                    {
                        Assert.IsTrue(queue.Contains(plane));
                    }
                    foreach (Plane plane in removed)
                    {
                        Assert.IsFalse(queue.Contains(plane));
                    }
                }
            }


            String treeTraversalLevelOrder = queue.TraverseLevelOrder();

            File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\pairingheapTestLevelOrder.txt",
                              treeTraversalLevelOrder);
            String treeTraversalInOrder = queue.TraverseInOrder();

            File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\pairingheapTestInOrder.txt",
                              treeTraversalInOrder);
            String checkInfo = "ADD checks: " + addCount + "\r\nSuccessfully added elements: " + succAddCount +
                               "\r\nCHANGE PRIORITY checks: " + changePriorityCount + "\r\nSuccessfully changed priorities: " + succChangePriorityCount +
                               "\r\nDELETE checks: " + deleteCount + "\r\nSuccessfully deleted elements: " + succDeleteCount +
                               "\r\nQueue-List comparisons: " + compareCheck;

            File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\pairingheapTestStats.txt",
                              checkInfo);
            File.WriteAllText("D:\\.NET Projects\\PlaneDepartureTracking\\PlaneDepartureTrackingMSTest\\pairingheapTestHistory.txt",
                              history);
        }
Ejemplo n.º 10
0
        public IEnumerable<Tuple<Word, int>> Derive()
        {
            var derivedWords = new HashSet<string>();
            var pq = new PairingHeap<Word, int>();

            pq.Add(new Word(Grammar.StartSymbol), 0);

            var rules = Grammar.Rules.OrderBy(r => r.WordToInsert.Length - r.WordToReplace.Length).ToArray();

            while (pq.Count > 0)
            {
                var elementToDerive = pq.Min;
                pq.Remove(elementToDerive);

                var wordToDerive = elementToDerive.Key;

                foreach (var nw in rules.SelectMany(rule => wordToDerive.ReplaceAll(rule.WordToReplace, rule.WordToInsert))
                        .Where(nw => !derivedWords.Contains(nw.ToString())))
                {
                    derivedWords.Add(nw.ToString());
                    pq.Add(nw, nw.Length);

                    yield return Tuple.Create(nw, wordToDerive.Length);
                }
            }
        }