Exemple #1
0
        private static string DecodeText(CombinedNode tree, string encodedText)
        {
            var   result      = "";
            var   offset      = 0;
            INode currentNode = tree;

            while (offset < encodedText.Length)
            {
                if (currentNode is CombinedNode combinedNode)
                {
                    if (encodedText[offset] == '0')
                    {
                        currentNode = combinedNode.LHS;
                    }
                    else
                    {
                        currentNode = combinedNode.RHS;
                    }
                }

                if (currentNode is LeafNode leafNode)
                {
                    result     += leafNode.Key;
                    currentNode = tree;
                }

                offset++;
            }
            return(result);
        }
Exemple #2
0
        private static CombinedNode BuildTree(IEnumerable <LeafNode> lettersByFrequency)
        {
            var leafQueue     = new Queue <LeafNode>();
            var combinedQueue = new Queue <CombinedNode>();

            foreach (var item in lettersByFrequency)
            {
                leafQueue.Enqueue(item);
            }

            while (leafQueue.Count() + combinedQueue.Count() > 1)
            {
                var lhs          = GetLowestItem(leafQueue, combinedQueue);
                var rhs          = GetLowestItem(leafQueue, combinedQueue);
                var combinedNode = new CombinedNode(lhs, rhs);
                combinedQueue.Enqueue(combinedNode);
            }
            return(combinedQueue.Dequeue());
        }