Beispiel #1
0
        private static int[] PriorityQueue(int[][] data)
        {
            MinPriorityQueue <Indices> queue = new MinPriorityQueue <Indices>();

            foreach (int[] array in data)
            {
                if (array.Length > 0)
                {
                    queue.Insert(new Indices {
                        Index = 0, Array = array
                    });
                }
            }

            int[] results = new int[data.Select(d => d.Length).Sum()];

            for (int i = 0; i < results.Length; i++)
            {
                Indices current = queue.Pop();
                results[i] = current.Array[current.Index];
                current.Index++;
                if (current.Index != current.Array.Length)
                {
                    queue.Insert(current);
                }
            }

            return(results);
        }
Beispiel #2
0
 public Huffman(IEnumerable<KeyValuePair<char, int>> kvps)
 {
     //保存原始数据
     var tmpOriginalNodes = from kvp in kvps select new HuffmanNode(kvp.Key, kvp.Value);
     //创建最小优先队列,并输入数据
     MinPriorityQueue<HuffmanNode> minQueue = new MinPriorityQueue<HuffmanNode>();
     originalNodes = new List<HuffmanNode>();
     foreach (var node in tmpOriginalNodes)
     {
         originalNodes.Add(node);
         minQueue.Insert(node);
     }
     //建造编码树,并取得编码树的根节点
     while (!minQueue.IsEmpty)
     {
         HuffmanNode left = minQueue.ExtractMin();
         if (minQueue.IsEmpty)
         {
             rootNode = left;
             break;
         }
         HuffmanNode right = minQueue.ExtractMin();
         HuffmanNode newNode = new HuffmanNode(null, left.Value + right.Value, left, right);
         left.Parent = newNode;
         right.Parent = newNode;
         minQueue.Insert(newNode);
     }
 }
Beispiel #3
0
        public Huffman(IEnumerable <KeyValuePair <char, int> > kvps)
        {
            //保存原始数据
            var tmpOriginalNodes = from kvp in kvps select new HuffmanNode(kvp.Key, kvp.Value);
            //创建最小优先队列,并输入数据
            MinPriorityQueue <HuffmanNode> minQueue = new MinPriorityQueue <HuffmanNode>();

            originalNodes = new List <HuffmanNode>();
            foreach (var node in tmpOriginalNodes)
            {
                originalNodes.Add(node);
                minQueue.Insert(node);
            }
            //建造编码树,并取得编码树的根节点
            while (!minQueue.IsEmpty)
            {
                HuffmanNode left = minQueue.ExtractMin();
                if (minQueue.IsEmpty)
                {
                    rootNode = left;
                    break;
                }
                HuffmanNode right   = minQueue.ExtractMin();
                HuffmanNode newNode = new HuffmanNode(null, left.Value + right.Value, left, right);
                left.Parent  = newNode;
                right.Parent = newNode;
                minQueue.Insert(newNode);
            }
        }
Beispiel #4
0
 private void Run(IGraph g, int s)
 {
     //set the weight to source vertex s as 0
     _distTo[s] = 0.0;
     //insert the vertex into the priority queue as (vertex number, weight)
     _pq.Insert(s, _distTo[s]);
     while (!_pq.IsEmpty())
     {
         //remove a vertex from the top of the queue
         var v = _pq.DeleteMin();
         Scan(g, v);
     }
 }
Beispiel #5
0
        public void Run(int vertex)
        {
            _distanceTo[vertex] = 0.0;
            _priorityQueue.Insert(vertex, _distanceTo[vertex]);

            while (!_priorityQueue.IsEmpty())
            {
                var v = _priorityQueue.DeleteMin();
                foreach (var neighbour in _graph.Neighbours(v))
                {
                    Relax(neighbour);
                }
            }
        }
Beispiel #6
0
        public void Insert_into_a_full_queue_should_lead_to_an_exception()
        {
            var queue = new MinPriorityQueue <int>(3);

            queue.Insert(_fixture.Create <int>());
            queue.Insert(_fixture.Create <int>());
            queue.Insert(_fixture.Create <int>());

            Action act = () => queue.Insert(_fixture.Create <int>());

            act
            .Should()
            .Throw <InvalidOperationException>()
            .WithMessage("The queue is full.");
        }
        private void InitServices()
        {
            while (m_ServicesToInit.Count > 0)
            {
                var serviceNameToInit = m_ServicesToInit.Dequeue();
                var serviceInstance   = m_ServiceNameToSingletonMap[serviceNameToInit];
                var bindingData       = (BindingData)m_ServiceNameToBindingDataMap[serviceNameToInit];

                if (!bindingData.LifeCycleManaged)
                {
                    continue;
                }

                if (!(serviceInstance is ILifeCycle lifeCycleInstance))
                {
                    continue;
                }

                m_ServiceInitCounter++;
                InvokeCallbacks(serviceInstance, bindingData.OnPreInitCallbacks);
                lifeCycleInstance.OnInit();
                InvokeCallbacks(serviceInstance, bindingData.OnPostInitCallbacks);
                ServicesToShutdown.Insert(serviceNameToInit, lifeCycleInstance, -m_ServiceInitCounter);
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            MaxPriorityQueue <IHeapValue> maxheap = new MaxPriorityQueue <IHeapValue>();
            MinPriorityQueue <IHeapValue> minheap = new MinPriorityQueue <IHeapValue>();
            List <IHeapValue>             list    = new List <IHeapValue>();
            Random rnd = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < 10; i++)
            {
                HeapNode hn = new HeapNode()
                {
                    Value = rnd.Next(0, 100)
                };
                list.Add(hn);
                maxheap.Insert(hn);
                minheap.Insert(hn);
            }
            Console.WriteLine("RandomData:");
            list.ForEach(n => Console.Write("{0},", n.Value));
            Console.WriteLine(Environment.NewLine + "MaxHeapOutput:");
            while (!maxheap.IsEmpty)
            {
                Console.Write("{0},", maxheap.ExtractMax().Value);
            }
            Console.WriteLine(Environment.NewLine + "MinHeapOutput:");
            while (!minheap.IsEmpty)
            {
                Console.Write("{0},", minheap.ExtractMin().Value);
            }
            Console.ReadKey();
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            MaxPriorityQueue<IHeapValue> maxheap = new MaxPriorityQueue<IHeapValue>();
            MinPriorityQueue<IHeapValue> minheap = new MinPriorityQueue<IHeapValue>();
            List<IHeapValue> list = new List<IHeapValue>();
            Random rnd = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < 10; i++)
            {
                HeapNode hn = new HeapNode() { Value = rnd.Next(0, 100) };
                list.Add(hn);
                maxheap.Insert(hn);
                minheap.Insert(hn);
            }
            Console.WriteLine("RandomData:");
            list.ForEach(n => Console.Write("{0},", n.Value));
            Console.WriteLine(Environment.NewLine + "MaxHeapOutput:");
            while (!maxheap.IsEmpty)
            {
                Console.Write("{0},", maxheap.ExtractMax().Value);
            }
            Console.WriteLine(Environment.NewLine + "MinHeapOutput:");
            while (!minheap.IsEmpty)
            {
                Console.Write("{0},", minheap.ExtractMin().Value);
            }
            Console.ReadKey();

        }
        public void TestSimple()
        {
            var values = new List <int> {
                3, 5, 2, 4, 1, 7, 8, 6
            };
            var q = new MinPriorityQueue <int, int>();

            Assert.AreEqual(0, q.Count);
            foreach (var v in values)
            {
                q.Insert(v, v, v);
            }

            Assert.AreEqual(values.Count, q.Count);
            AssertMinHeap(q);
            AssertIndices(q);

            int min = 0;

            while (q.Count > 0)
            {
                min++;
                Assert.AreEqual(min, q.Min.Key);
                Assert.AreEqual(min, q.Min.Value);
                Assert.AreEqual(min, q.Min.Priority);
                q.PopMin();
            }

            Assert.Throws <InvalidOperationException>(() => { q.PopMin(); });
        }
        public void TestInsertAndDelete()
        {
            var values = new List <int>
            {
                31, 30, 28, 29, 26, 19, 27, 21, 20, 10, 25, 18, 11, 24, 15, 17, 6, 12, 13, 1, 7, 16, 9, 3, 2, 4, 8, 23, 22, 5, 14
            };
            var q     = new MinPriorityQueue <int, int>();
            int count = 0;

            foreach (var v in values)
            {
                q.Insert(v + 100, v + 200, v);
                count++;
                Assert.AreEqual(count, q.Count);
                AssertMinHeap(q);
                AssertIndices(q);
            }

            Assert.False(q.Remove(19));
            Assert.True(q.Any(node => node.Key == 119));
            Assert.True(q.Any(node => node.Value == 219));
            Assert.True(q.Any(node => node.Priority == 19));
            Assert.True(q.Remove(119));
            AssertMinHeap(q);
            AssertIndices(q);
            Assert.False(q.Any(node => node.Key == 119));
            Assert.False(q.Any(node => node.Value == 219));
            Assert.False(q.Any(node => node.Priority == 19));
            Assert.False(q.Remove(119));
        }
Beispiel #12
0
        public static Edge[] Run(Vertex[] vertices)
        {
            PriorityQueue <Node> queue = new MinPriorityQueue <Node>();

            vertices[0].Depth = 0;
            queue.Insert(new Node(vertices[0]));

            while (!queue.IsEmpty)
            {
                Vertex current = queue.Pop().Vertex;
                current.Color = Color.Black;

                foreach (Edge edge in current.Edges)
                {
                    if (edge.To.Color == Color.Black)
                    {
                        continue;
                    }

                    if (edge.To.Depth > edge.Weight)
                    {
                        edge.To.Depth  = edge.Weight;
                        edge.To.Parent = current;
                        queue.Insert(new Node(edge.To));
                    }
                }
            }

            Edge[] results = new Edge[vertices.Length - 1];

            for (int i = 0; i < results.Length; i++)
            {
                foreach (Edge edge in vertices[i + 1].Edges)
                {
                    if (edge.To == vertices[i + 1].Parent)
                    {
                        results[i] = edge;
                        break;
                    }
                }
            }

            return(results);
        }
 private void Visit(EdgeWeightedGraph g, int v)
 {
     marked[v] = true;
     foreach (var e in g.Adj(v))
     {
         if (!marked[e.Other(v)])
         {
             pq.Insert(e);
         }
     }
 }
Beispiel #14
0
        public static int Run(int[] nums, int k)
        {
            var pq = new MinPriorityQueue(k);

            for (int i = 0; i < k; ++i)
            {
                pq.Insert(nums[i]);
            }

            for (int i = k; i < nums.Length; ++i)
            {
                if (nums[i] > pq.Peek())
                {
                    pq.Pop();
                    pq.Insert(nums[i]);
                }
            }

            return(pq.Pop());
        }
 public void MinPQ_Basic()
 {
     var pq = new MinPriorityQueue<int>();
     pq.Insert(2, null);
     pq.Insert(6, null);
     pq.Insert(1, null);
     Assert.AreEqual(1, (int)(pq.DelMax().Item1));
     pq.Insert(9, null);
     pq.Insert(7, null);
     pq.Insert(1, null);
     Assert.AreEqual(1, (int)(pq.DelMax().Item1));
     pq.Insert(2, null);
     pq.Insert(6, null);
     pq.Insert(1, null);
     Assert.AreEqual(1, (int)(pq.DelMax().Item1));
     Assert.AreEqual(2, (int)(pq.Max().Item1));
     Assert.AreEqual(2, (int)(pq.DelMax().Item1));
     Assert.AreEqual(2, (int)(pq.DelMax().Item1));
     Assert.AreEqual(6, (int)(pq.DelMax().Item1));
 }
Beispiel #16
0
        public static MinPriorityQueue <TrieNode> FromFrequencyTable(long[] frequencyTable)
        {
            var minQueue = new MinPriorityQueue <TrieNode>(2 * CodeTable.Size - 1);

            for (var i = 0; i < frequencyTable.Length; i++)
            {
                if (frequencyTable[i] > 0)
                {
                    var node = TrieNode.CreateLeaf((byte)i, frequencyTable[i]);
                    minQueue.Insert(node);
                }
            }

            return(minQueue);
        }
Beispiel #17
0
        public void MinPQ_Basic()
        {
            var pq = new MinPriorityQueue <int>();

            pq.Insert(2, null);
            pq.Insert(6, null);
            pq.Insert(1, null);
            Assert.AreEqual(1, (int)(pq.DelTop().Item1));
            pq.Insert(9, null);
            pq.Insert(7, null);
            pq.Insert(1, null);
            Assert.AreEqual(1, (int)(pq.DelTop().Item1));
            pq.Insert(2, null);
            pq.Insert(6, null);
            pq.Insert(1, null);
            Assert.AreEqual(1, (int)(pq.DelTop().Item1));
            Assert.AreEqual(2, (int)(pq.Top().Item1));
            Assert.AreEqual(2, (int)(pq.DelTop().Item1));
            Assert.AreEqual(2, (int)(pq.DelTop().Item1));
            Assert.AreEqual(6, (int)(pq.DelTop().Item1));
        }
Beispiel #18
0
        public void MinPriorityQueueTest()
        {
            int[] xs    = { 3, 2, 1, 6, 5, 9, 4 };
            var   queue = new MinPriorityQueue <int>(xs.Length);

            for (int i = 0; i < xs.Length; i++)
            {
                queue.Insert(xs[i]);
            }
            Quick <int> .SimpleSort(xs);

            for (int i = 0; i < xs.Length; i++)
            {
                int v = queue.DelMin();
                Assert.Equal(v, xs[i]);
            }
        }
Beispiel #19
0
        private IEnumerable <T> PutIntoQueueAndTakeBack <T>(T[] input) where T : IComparable <T>
        {
            var queue = new MinPriorityQueue <T>(input.Length);

            foreach (var item in input)
            {
                queue.Insert(item);
            }

            var result = new List <T>();

            while (!queue.IsEmpty)
            {
                result.Add(queue.RemoveMin());
            }

            return(result);
        }
Beispiel #20
0
        public void MinPriorityQueueTest()
        {
            var pq = new MinPriorityQueue <string>(9);

            var results = new List <string>();

            pq.Insert("P");
            pq.Insert("Q");
            pq.Insert("E");

            results.Add(pq.DeleteMin());

            pq.Insert("X");
            pq.Insert("A");
            pq.Insert("M");

            results.Add(pq.DeleteMin());

            pq.Insert("P");
            pq.Insert("L");
            pq.Insert("E");

            results.Add(pq.DeleteMin());
        }
        public void MinPriorityQueueTest_Comparer()
        {
            Point[] points = new Point[10];
            for (int i = 0; i < 10; i++)
            {
                points[i] = new Point(i, 10 - i);
            }
            Shuffle.Do(points);

            MinPriorityQueue <Point> pq = new MinPriorityQueue <Point>(Point.X_ORDER);

            foreach (var value in points)
            {
                pq.Insert(value);
            }
            Assert.IsFalse(pq.IsEmpty());
            Assert.AreEqual(10, pq.Size());

            Point[] expectPoints = new Point[10];
            for (int i = 0; i < 10; i++)
            {
                expectPoints[i] = new Point(i, 10 - i);
            }
            Shuffle.Do(expectPoints);
            HeapSort.Sort(expectPoints, Point.X_ORDER, SortOrder.ASC);

            for (int i = 0; i < 10; i++)
            {
                var result = pq.Min();
                Assert.AreEqual(expectPoints[i].X, result.X);
                Assert.AreEqual(expectPoints[i].Y, result.Y);
                result = pq.DelMin();
                Assert.AreEqual(expectPoints[i].X, result.X);
                Assert.AreEqual(expectPoints[i].Y, result.Y);
            }
            Assert.IsTrue(pq.IsEmpty());
            Assert.AreEqual(0, pq.Size());
        }
        public void MinPriorityQueueTest_Enumerator()
        {
            int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Shuffle.Do(a);

            MinPriorityQueue <int> pq = new MinPriorityQueue <int>();

            foreach (var value in a)
            {
                pq.Insert(value);
            }
            Assert.IsFalse(pq.IsEmpty());
            Assert.AreEqual(10, pq.Size());

            int expectedValue = 0;

            foreach (var value in pq)
            {
                Assert.AreEqual(expectedValue++, value);
            }
            Assert.IsFalse(pq.IsEmpty());
            Assert.AreEqual(10, pq.Size());
        }
    public bool DoTest()
    {
        Random     random = new Random(Guid.NewGuid().GetHashCode());
        List <int> nums   = new List <int>();

        for (int i = 0; i < INIT_NUM; i++)
        {
            nums.Add(random.Next(NUM_RANGE));
        }

        MinPriorityQueue <int> testPq = new MinPriorityQueue <int>(nums.GetEnumerator());

        for (int i = 0; i < INSERT_NUM; i++)
        {
            testPq.Insert(random.Next(NUM_RANGE));
        }
        List <int> orginNums  = new List <int>();
        List <int> sortedNums = new List <int>();

        while (!testPq.IsEmpty())
        {
            int top = testPq.DelTop();
            orginNums.Add(top);
            sortedNums.Add(top);
        }
        sortedNums.Sort();

        for (int i = 0; i < orginNums.Count; i++)
        {
            if (orginNums[i] != sortedNums[i])
            {
                return(false);
            }
        }

        return(true);
    }
        public void MinPriorityQueueTest_Insert()
        {
            int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Shuffle.Do(a);

            MinPriorityQueue <int> pq = new MinPriorityQueue <int>();

            foreach (var value in a)
            {
                pq.Insert(value);
            }
            Assert.IsFalse(pq.IsEmpty());
            Assert.AreEqual(10, pq.Size());

            for (int i = 0; i < 10; i++)
            {
                int result = pq.Min();
                Assert.AreEqual(i, result);
                result = pq.DelMin();
                Assert.AreEqual(i, result);
            }
            Assert.IsTrue(pq.IsEmpty());
            Assert.AreEqual(0, pq.Size());
        }
Beispiel #25
0
        public KruskalMinimumSpanTree(EdgeWeightedGraph g)
        {
            mst = new List <Edge>();
            var pq = new MinPriorityQueue <Edge>(g.Ecount);

            foreach (var e in g.Edges())
            {
                pq.Insert(e);
            }
            var uf = new UF(g.Vcount);

            while (!pq.IsEmpty() && mst.Count < g.Vcount - 1)
            {
                var e = pq.DelMin();
                int v = e.Either;
                int w = e.Other(v);
                if (uf.Connected(v, w))
                {
                    continue;
                }
                uf.Union(v, w);
                mst.Add(e);
            }
        }