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());
        }
Exemplo n.º 2
0
    void Merge(PairingHeap <T> other)
    {
        if (Empty && !other.Empty)
        {
            root     = other.root;
            children = other.children;
        }
        else if (!Empty && !other.Empty)
        {
            int ourPrio   = root.priority;
            int otherPrio = other.root.priority;
            if (ourPrio < otherPrio)
            {
                children.Add(other);
            }
            else
            {
                PairingHeap <T> us = new PairingHeap <T>(root.item, root.priority);
                us.children = new List <PairingHeap <T> >(children);

                root.item     = other.root.item;
                root.priority = other.root.priority;
                children      = other.children;
                children.Add(us);
            }
        }
    }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
 public TrackType(double length)
 {
     Length                 = length;
     Tracks                 = new List <Track>();
     WaitingPlanes          = new PairingHeap <Plane, double>();
     WaitingPlanesForSearch = new SplayTree <Plane>();
 }
Exemplo n.º 5
0
    public void Enqueue(T item)
    {
        var heap = new PairingHeap <T>(item);

        top = PairingHeap <T> .Merge(top, heap, compare);

        size++;
    }
Exemplo n.º 6
0
 public static void Print <TNode, TKey, TValue>([NotNull] this PairingHeap <TNode, TKey, TValue> thisValue)
     where TNode : PairingNode <TNode, TKey, TValue>
 {
     Console.WriteLine();
     Console.WriteLine("Count: " + thisValue.Count);
     Console.WriteLine();
     thisValue.WriteTo(Console.Out);
 }
Exemplo n.º 7
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);
        }
        public void OneValueTest()
        {
            PairingHeap <int> pairingHeap = new PairingHeap <int>((x, y) => x > y);

            pairingHeap.Insert(10);
            var value = pairingHeap.ExtractMinimum();

            Assert.Equal(10, value.value);
        }
Exemplo n.º 9
0
    public T Dequeue()
    {
        var ret = top.Key;

        size--;
        top = PairingHeap <T> .Pop(top, compare);

        return(ret);
    }
Exemplo n.º 10
0
        public void BuildMinHeap_CheckEnumerator_NotThrowOnEnumerate()
        {
            var minHeap = new PairingHeap <int>();

            minHeap.Insert(1);

            var items = minHeap.ToList();

            items.Should().HaveCount(1);
        }
Exemplo n.º 11
0
        public void BuildMinHeap_UpdateBadNode_ThrowException()
        {
            var minHeap = new PairingHeap <int>();

            minHeap.Insert(10);

            Action act = () => minHeap.UpdateKey(10, 11);

            act.Should().Throw <ArgumentException>();
        }
Exemplo n.º 12
0
        public void BuildMinHeap_CheckEnumerable_NotThrowOnEnumerate()
        {
            var minHeap = new PairingHeap <int>();

            minHeap.Insert(1);

            foreach (var node in (IEnumerable)minHeap)
            {
                node.Should().NotBe(null);
            }
        }
Exemplo n.º 13
0
        public void Max_PairingHeap_Test()
        {
            int nodeCount = 1000 * 10;

            var maxHeap = new PairingHeap <int>(SortDirection.Descending);

            for (int i = 0; i <= nodeCount; i++)
            {
                maxHeap.Insert(i);
            }

            for (int i = 0; i <= nodeCount; i++)
            {
                maxHeap.UpdateKey(i, i + 1);
            }

            //IEnumerable tests.
            Assert.AreEqual(maxHeap.Count, maxHeap.Count());

            int max = 0;

            for (int i = nodeCount; i >= 0; i--)
            {
                max = maxHeap.Extract();
                Assert.AreEqual(max, i + 1);
            }

            var rnd        = new Random();
            var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(x => rnd.Next()).ToList();

            foreach (var item in testSeries)
            {
                maxHeap.Insert(item);
            }

            for (int i = 0; i < testSeries.Count; i++)
            {
                var incremented = testSeries[i] + rnd.Next(0, 1000);
                maxHeap.UpdateKey(testSeries[i], incremented);
                testSeries[i] = incremented;
            }

            testSeries = testSeries.OrderByDescending(x => x).ToList();

            for (int i = 0; i < nodeCount - 2; i++)
            {
                max = maxHeap.Extract();
                Assert.AreEqual(testSeries[i], max);
            }

            //IEnumerable tests.
            Assert.AreEqual(maxHeap.Count, maxHeap.Count());
        }
Exemplo n.º 14
0
        public void Min_PairingHeap_Test()
        {
            int nodeCount = 1000 * 10;

            var minHeap = new PairingHeap <int>();

            for (int i = 0; i <= nodeCount; i++)
            {
                minHeap.Insert(i);
            }

            for (int i = 0; i <= nodeCount; i++)
            {
                minHeap.UpdateKey(i, i - 1);
            }

            int min = 0;

            for (int i = 0; i <= nodeCount; i++)
            {
                min = minHeap.Extract();
                Assert.AreEqual(min, i - 1);
            }

            //IEnumerable tests.
            Assert.AreEqual(minHeap.Count, minHeap.Count());

            var rnd        = new Random();
            var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(x => rnd.Next()).ToList();

            foreach (var item in testSeries)
            {
                minHeap.Insert(item);
            }

            for (int i = 0; i < testSeries.Count; i++)
            {
                var decremented = testSeries[i] - rnd.Next(0, 1000);
                minHeap.UpdateKey(testSeries[i], decremented);
                testSeries[i] = decremented;
            }

            testSeries.Sort();

            for (int i = 0; i < nodeCount - 2; i++)
            {
                min = minHeap.Extract();
                Assert.AreEqual(testSeries[i], min);
            }

            //IEnumerable tests.
            Assert.AreEqual(minHeap.Count, minHeap.Count());
        }
Exemplo n.º 15
0
 static public PairingHeap <T> Merge(PairingHeap <T> l, PairingHeap <T> r, Comparison <T> compare)
 {
     if (l == null || r == null)
     {
         return(l == null ? r : l);
     }
     if (compare(l.key, r.key) > 0)
     {
         Swap(ref l, ref r);
     }
     r.next = l.head;
     l.head = r;
     return(l);
 }
Exemplo n.º 16
0
        public void Initialize()
        {
            var random = new Random(42);

            _priorities = new int[Size];
            for (int i = 0; i < Size; i++)
            {
                _priorities[i] = random.Next();
            }

            _prioritySet      = new PrioritySet <int, int>(initialCapacity: Size);
            _pairingHeap      = new PairingHeap <int, int>(Comparer <int> .Default);
            _pairingHeapNodes = new Dictionary <int, PairingHeapNode <int, int> >(Size);
        }
        /// <summary>
        ///     Computes the minimum spanning tree for the connected component containing a specified vertex.
        /// </summary>
        /// <param name="startVertex">The vertex where the algorithm should start.</param>
        /// <returns>The set of edges that define the minimum spanning tree.</returns>
        public ReadOnlySpan <TEdgeId> ComputeMinimumSpanningTree(TVertexId startVertex)
        {
            var heapNodes = new Dictionary <TVertexId, PairingHeap <VertexWithDistanceAndEdge> .ElementPointer>(this._graph.Comparer)
            {
                { startVertex, PairingHeap <VertexWithDistanceAndEdge> .ElementPointer.Undefined }
            };
            var todo   = new PairingHeap <VertexWithDistanceAndEdge>(new DistanceComparer(this._comparer));
            var result = new DynamicArray <TEdgeId>(true);

            ProcessEdges(startVertex);
            while (todo.TryExtractMinimum(out var next))
            {
                heapNodes[next.Vertex] = PairingHeap <VertexWithDistanceAndEdge> .ElementPointer.Undefined;
                result.AddLast(next.Edge);
                ProcessEdges(next.Vertex);
            }

            return(result.AsSpan());

            void ProcessEdges(TVertexId vertex)
            {
                foreach (var outEdgeIdx in this._graph.GetOutEdges(vertex))
                {
                    var target = this._graph.GetTarget(outEdgeIdx);
                    if (heapNodes.TryGetValue(target, out var vertexState))
                    {
                        if (vertexState.IsUndefined)
                        {
                            continue;
                        }

                        var currentBestDistanceToTarget = todo[vertexState].Distance;
                        var distance = this._graph.GetEdgeTag(outEdgeIdx);
                        if (this._comparer.Compare(distance, currentBestDistanceToTarget) >= 0)
                        {
                            continue;
                        }

                        todo.Decrease(vertexState, new(target, distance, outEdgeIdx));
                    }
                    else
                    {
                        var distance = this._graph.GetEdgeTag(outEdgeIdx);
                        var node     = todo.Insert(new(target, distance, outEdgeIdx));
                        heapNodes.Add(target, node);
                    }
                }
            }
        }
Exemplo n.º 18
0
        public void BuildMaxHeap_CreateHeap_HeapIsCheked()
        {
            var nodeCount = 1000 * 10;
            var maxHeap   = new PairingHeap <int>(Sorting.Descending);

            for (var i = 0; i <= nodeCount; i++)
            {
                maxHeap.Insert(i);
            }

            for (var i = 0; i <= nodeCount; i++)
            {
                maxHeap.UpdateKey(i, i + 1);
            }

            Assert.AreEqual(maxHeap.Count, maxHeap.Count);

            var max = 0;

            for (var i = nodeCount; i >= 0; i--)
            {
                max = maxHeap.Extract();
                Assert.AreEqual(max, i + 1);
            }

            var rnd        = new Random();
            var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(_ => rnd.Next()).ToList();

            foreach (var item in testSeries)
            {
                maxHeap.Insert(item);
            }

            for (var i = 0; i < testSeries.Count; i++)
            {
                var incremented = testSeries[i] + rnd.Next(0, 1000);
                maxHeap.UpdateKey(testSeries[i], incremented);
                testSeries[i] = incremented;
            }

            testSeries = testSeries.OrderByDescending(x => x).ToList();
            for (var i = 0; i < nodeCount - 2; i++)
            {
                max = maxHeap.Extract();
                Assert.AreEqual(testSeries[i], max);
            }

            Assert.AreEqual(maxHeap.Count, maxHeap.Count);
        }
Exemplo n.º 19
0
        public void Initialize()
        {
            var random = new Random(42);

            _priorities = new int[2 * Size];
            for (int i = 0; i < 2 * Size; i++)
            {
                _priorities[i] = random.Next();
            }

            _priorityQueue2 = new PriorityQueue <int>(initialCapacity: Size);
            _priorityQueue  = new PriorityQueue <int, int>(initialCapacity: Size);
            _prioritySet    = new PrioritySet <int, int>(initialCapacity: Size);
            _pairingHeap    = new PairingHeap <int, int>(Comparer <int> .Default);
        }
Exemplo n.º 20
0
        public static (bool connected, Graph tree) Prim(this Graph g, int startingVertex = 0)
        {
            if (g.Directed)
            {
                throw new WrongGraphException("Graph must be an undirected graph");
            }

            if (startingVertex < 0 || startingVertex >= g.VerticesCount)
            {
                throw new ArgumentOutOfRangeException("startingVertex");
            }

            Graph tree = g.IsolatedGraph(g.Directed);
            PairingHeap <Edge> queue = new PairingHeap <Edge>((x, y) => x.Weight > y.Weight);

            UnionFind unionFind = new UnionFind(g.VerticesCount);

            foreach (var e in g.GetEdgesFrom(startingVertex))
            {
                queue.Insert(e);
            }

            int c = 0;

            while (true)
            {
                if (queue.IsEmpty() || c == g.VerticesCount - 1)
                {
                    return(c == g.VerticesCount - 1 ? true : false, tree);
                }

                var e = queue.ExtractMinimum();

                if (unionFind.FindParent(e.value.From) != unionFind.FindParent(e.value.To))
                {
                    tree.AddEdge(e.value);

                    unionFind.Union(e.value.From, e.value.To);

                    foreach (var f in g.GetEdgesFrom(e.value.To))
                    {
                        queue.Insert(f);
                    }

                    c++;
                }
            }
        }
                protected bool Find(T item, out PairingHeap <T> heap, out LinkedListNode <PairingHeap <T> > node)
                {
                    heap = null; node = null;

                    if (this.root.CompareTo(item) == 0)
                    {
                        heap = this;
                        return(true);
                    }

                    if (this.children.Count == 0)
                    {
                        return(false);
                    }

                    Stack <LinkedListNode <PairingHeap <T> > > stack   = new Stack <LinkedListNode <PairingHeap <T> > >();
                    LinkedListNode <PairingHeap <T> >          current = this.children.First;

                    stack.Push(new LinkedListNode <PairingHeap <T> >(this));
                    while (stack.Count > 0)
                    {
                        if (current.Value.root.CompareTo(item) == 0)
                        {
                            heap = current.Value;
                            node = current;
                            return(true);
                        }

                        if (current.Value.children.Count > 0)
                        {
                            if (current.Next != null)
                            {
                                stack.Push(current.Next);
                            }
                            current = current.Value.children.First;
                        }
                        else if (current.Next != null)
                        {
                            current = current.Next;
                        }
                        else
                        {
                            current = stack.Pop();
                        }
                    }

                    return(false);
                }
    // Test program
    public static void Main(string[] args)
    {
        PairingHeap <int> h = new PairingHeap <int>( );
        int numItems        = 10000;
        int i = 37;
        int j;

        Console.WriteLine("Checking; no bad output is good");
        for (i = 37; i != 0; i = (i + 37) % numItems)
        {
            h.Insert(i);
        }
        for (i = 1; i < numItems; i++)
        {
            if (h.DeleteMin( ) != i)
            {
                Console.WriteLine("Oops! " + i);
            }
        }

        List <IPriorityQueuePosition <int> > p = new List <IPriorityQueuePosition <int> >( );

        for (i = 0; i < numItems; i++)
        {
            p.Add(null);
        }

        for (i = 0, j = numItems / 2; i < numItems; i++, j = (j + 71) % numItems)
        {
            p[j] = h.Insert(j + numItems);
        }
        for (i = 0, j = numItems / 2; i < numItems; i++, j = (j + 53) % numItems)
        {
            h.DecreaseKey(p[j], p[j].GetValue( ) - numItems);
        }
        i = -1;
        while (!h.IsEmpty( ))
        {
            if (h.DeleteMin( ) != ++i)
            {
                Console.WriteLine("Oops! " + i + " ");
            }
        }
        Console.WriteLine("Check completed");
    }
Exemplo n.º 23
0
        // Single-source weighted shortest-path algorithm using pairing heaps.
        public void Dijkstra2(string startName)
        {
            IPriorityQueue <Path> pq = new PairingHeap <Path>();

            Vertex start = vertexMap[startName]; // throws an exception if not found

            ClearAll();
            start.pos  = pq.Insert(new Path(start, 0));
            start.dist = 0;

            while (!pq.IsEmpty())
            {
                Path   vrec = pq.DeleteMin();
                Vertex v    = vrec.dest;

                foreach (Edge e in v.adj)
                {
                    Vertex w   = e.dest;
                    double cvw = e.cost;

                    if (cvw < 0)
                    {
                        throw new GraphException("Graph has negative edges");
                    }

                    if (w.dist > v.dist + cvw)
                    {
                        w.dist = v.dist + cvw;
                        w.prev = v;

                        Path newVal = new Path(w, w.dist);
                        if (w.pos == null)
                        {
                            w.pos = pq.Insert(newVal);
                        }
                        else
                        {
                            pq.DecreaseKey(w.pos, newVal);
                        }
                    }
                }
            }
        }
                /// <summary>
                /// Removes the first occurrence of a specific object from the PairingHeap&lt;T>.
                /// </summary>
                /// <param name="item">The object to be removed.</param>
                /// <returns><code>true</code> if item was successfully removed from the PairingHeap&lt;T>; otherwise, <code>false</code>.</returns>
                public bool Remove(T item)
                {
                    PairingHeap <T> heap, parent;
                    LinkedListNode <PairingHeap <T> > node;

                    if (this.Find(item, out heap, out node))
                    {
                        parent = heap;
                        while (parent != null)
                        {
                            parent.Count--;
                            parent = parent.parent;
                        }

                        heap.MergePairs();
                        return(true);
                    }

                    return(false);
                }
Exemplo n.º 25
0
        public static (bool connected, Graph tree) Kruskal(this Graph g)
        {
            if (g.Directed)
            {
                throw new WrongGraphException("Graph must be an undirected graph");
            }

            Graph tree = g.IsolatedGraph(g.Directed);
            PairingHeap <Edge> queue = new PairingHeap <Edge>((x, y) => x.Weight > y.Weight);

            UnionFind unionFind = new UnionFind(g.VerticesCount);

            for (int i = 0; i < g.VerticesCount; i++)
            {
                foreach (var e in g.GetEdgesFrom(i))
                {
                    queue.Insert(e);
                }
            }

            int c = 0;

            while (true)
            {
                if (queue.IsEmpty() || c == g.VerticesCount - 1)
                {
                    return(c == g.VerticesCount - 1 ? true : false, tree);
                }

                var e = queue.ExtractMinimum();

                if (unionFind.FindParent(e.value.From) != unionFind.FindParent(e.value.To))
                {
                    tree.AddEdge(e.value);
                    unionFind.Union(e.value.From, e.value.To);
                    c++;
                }
            }
        }
Exemplo n.º 26
0
 void MergePairs(List <PairingHeap <T> > l)
 {
     if (l.Count == 0)
     {
         return;
     }
     else if (l.Count == 1)
     {
         if (root == null)
         {
             root = l[0].root;
         }
         else
         {
             root.item     = l[0].root.item;
             root.priority = l[0].root.priority;
         }
         children = l[0].children;
     }
     else
     {
         PairingHeap <T> aux = new PairingHeap <T>();
         aux.Merge(l[0]);
         aux.Merge(l[1]);
         PairingHeap <T> aux2 = new PairingHeap <T>();
         aux2.MergePairs(l.GetRange(2, l.Count - 2));
         aux.Merge(aux2);
         if (root == null)
         {
             root = aux.root;
         }
         else
         {
             root.item     = aux.root.item;
             root.priority = aux.root.priority;
         }
         children = aux.children;
     }
 }
Exemplo n.º 27
0
        public void NValueTest(int n)
        {
            PairingHeap <int> pairingHeap = new PairingHeap <int>((x, y) => x > y);
            List <int>        lista       = new List <int>();

            Random random = new Random();

            for (int i = 0; i < n; i++)
            {
                int value = random.Next() % n * (0 == random.Next() % 2 ? -1 : 1);
                lista.Add(value);
                pairingHeap.Insert(value);
            }

            lista.Sort();

            for (int i = 0; i < n; i++)
            {
                var value = pairingHeap.ExtractMinimum();
                Assert.Equal(lista[i], value.value);
            }
        }
                /// <summary>
                /// Merges a heap into this one.
                /// </summary>
                /// <param name="other">The heap to merge into this one.</param>
                public override void Merge(PairingHeap <T> other)
                {
                    PairingMaxHeap <T> heap = other as PairingMaxHeap <T>;

                    if (heap == null)
                    {
                        this.AddRange(other);
                        return;
                    }

                    if (heap.Count == 0)
                    {
                        return;
                    }

                    if (this.Count == 0)
                    {
                        this.root     = heap.root;
                        this.children = heap.children;
                        this.Count    = heap.Count;
                        return;
                    }

                    this.Count += heap.Count;
                    if (this.root.CompareTo(heap.root) >= 0)
                    {
                        this.children.AddFirst(heap);
                        heap.parent = this;
                    }
                    else
                    {
                        PairingMaxHeap <T> newHeap = new PairingMaxHeap <T>(this.root, this.children, this.Count);
                        this.root     = heap.root;
                        this.children = heap.children;
                        this.children.AddFirst(newHeap);
                        newHeap.parent = this;
                    }
                }
Exemplo n.º 29
0
    static public PairingHeap <T> MergeLst(PairingHeap <T> s, Comparison <T> compare)
    {
        var n = new PairingHeap <T>(default(T));

        while (s != null)
        {
            PairingHeap <T> a = s, b = null;
            s = s.next; a.next = null;
            if (s != null)
            {
                b = s; s = s.next; b.next = null;
            }
            a      = Merge(a, b, compare); a.next = n.next;
            n.next = a;
        }
        while (n.next != null)
        {
            var j = n.next;
            n.next = n.next.next;
            s      = Merge(j, s, compare);
        }
        return(s);
    }
Exemplo n.º 30
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;
                }
            }
        }
Exemplo n.º 31
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);
                }
            }
        }
Exemplo n.º 32
0
 public OutstandingMessageCache()
 {
     _outstandingRequests = new Dictionary<Guid, OutstandingMessage>();
     _byTime = new PairingHeap<RetryableMessage>((x,y) => x.DueTime < y.DueTime);
     _bySequences = new SortedList<int, int>();
 }
 public void TearDown()
 {
     _heap = null;
 }
 public void SetUp()
 {
     _heap = new PairingHeap<int>();
 }