public static string Perform(string text)
        {
            var chars = text.ToCharArray();

            // Gathering alphabet frequency
            var alphabetFrequency = new Dictionary <char, int>();

            foreach (var c in chars) // First pass through the char array
            {
                if (!alphabetFrequency.ContainsKey(c))
                {
                    alphabetFrequency.Add(c, 1);
                }
                else
                {
                    alphabetFrequency[c] = alphabetFrequency[c] + 1;
                }
            }

            // Create binary heap
            var priorityQueue = new BinaryHeapPriorityQueue <TreeNode>(alphabetFrequency.Count, (i1, i2) => i2.Count.CompareTo(i1.Count));



            foreach (var entry in alphabetFrequency)
            {
                var leafNode = new LeafTreeNode(entry.Value);
                CharToNodes.Add(entry.Key, leafNode);
                priorityQueue.Insert(leafNode); // Initially PQ contains only leaf nodes
            }

            // Main part of the algorithm
            while (priorityQueue.GetSize() > 1)
            {
                var n1 = priorityQueue.Extract();
                var n2 = priorityQueue.Extract();

                var innerNode = new InnerTreeNode(n1, n2); // Creates a new node with sum of frequencies...

                priorityQueue.Insert(innerNode);           // ...and put it back
            } // Repeat the procedure untill PQ has only one element

            var root = priorityQueue.Extract();                       // Take the last element (root) from the PQ

            root.CreateCode(alphabetFrequency.Count == 1 ? "0" : ""); // Build codes for the whole hierarchy

            var sb = new StringBuilder();

            foreach (var t in chars) // Second pass through the char array
            {
                var c = CharToNodes[t].Code;
                sb.Append(c);
            }

            return(sb.ToString());
        }
示例#2
0
        public void GetSize_ValidParamsPassed_Success()
        {
            IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(5, (x, y) => - x.CompareTo(y));

            priorityQueue.Insert(5);
            priorityQueue.Insert(4);
            priorityQueue.Insert(3);

            var size = priorityQueue.GetSize();

            Assert.AreEqual(size, 3);
        }