Пример #1
0
        public void Encode(int value, List <int> encoding)
        {
            if (!_leafDictionary.ContainsKey(value))
            {
                throw new ArgumentException("Invalid value in Encode");
            }
            HuffmanNode <int> nodeCur = _leafDictionary[value];
            var reverseEncoding       = new List <int>();

            while (!nodeCur.IsRoot)
            {
                reverseEncoding.Add(nodeCur.Bit);
                nodeCur = nodeCur.Parent;
            }

            reverseEncoding.Reverse();
            encoding.AddRange(reverseEncoding);
        }
Пример #2
0
        public Huffman(Dictionary <int, int> counts)
        {
            var priorityQueue = new PriorityQueue <HuffmanNode <int> >();

            valueCount = counts.Count;

            foreach (int value in counts.Keys)
            {
                var node = new HuffmanNode <int>((double)counts[value] / valueCount, value);
                priorityQueue.Add(node);
                _leafDictionary[value] = node;
            }

            while (priorityQueue.Count > 1)
            {
                HuffmanNode <int> leftSon  = priorityQueue.Pop();
                HuffmanNode <int> rightSon = priorityQueue.Pop();
                var parent = new HuffmanNode <int>(leftSon, rightSon);
                priorityQueue.Add(parent);
            }

            _root        = priorityQueue.Pop();
            _root.IsZero = false;
        }