Exemplo n.º 1
0
 public HuffmanNode(HuffmanNode left, HuffmanNode right)
 {
     leaf = false;
     FrequencyCount = left.FrequencyCount + right.FrequencyCount;
     Left = left;
     Right = right;
 }
Exemplo n.º 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);
     }
 }
Exemplo n.º 3
0
        void PrintNode( HuffmanNode<int> node, string bits )
        {
            if( node == null ) return;

            if( node.HasValue ) {
                Console.WriteLine( node.Value + " : " + bits );
            } else {
                PrintNode( node.Left, "0" + bits );
                PrintNode( node.Right, "1" + bits );
            }
        }
        private static List<HuffmanNode> createHuffmanNodes(Dictionary<char, int> charFrequency)
        {
            var huffmanNodes = new List<HuffmanNode>(capacity: charFrequency.Keys.Count());

            foreach (char c in charFrequency.Keys)
            {
                var huffmanNode = new HuffmanNode { Characters = c.ToString(), NumOccurrences = charFrequency[c] };
                huffmanNodes.Add(huffmanNode);
            }

            return huffmanNodes;
        }
        private static void determineHuffmanCodesOfLeafNodes(HuffmanNode node, BitArray shortestBinaryCode)
        {
            const bool Zero = false;
            const bool One = true;

            if (node.IsLeaf)
            {
                node.HuffmanCode = shortestBinaryCode;
                return;
            }

            determineHuffmanCodesOfLeafNodes(node.Left, shortestBinaryCode.WithAppendedValue(Zero));
            determineHuffmanCodesOfLeafNodes(node.Right, shortestBinaryCode.WithAppendedValue(One));
        }
Exemplo n.º 6
0
        //
        //recurses through the entire tree and stacks up the respective code, then adds the respective symbol and code to the HuffmanTable when reaching a leave
        public void ConvertTreeToTable(List<bool> code, HuffmanNode node)
        {
            if (node == null)
                return;
            if (node.isLeaf == true)
            {
                huffmanTable.Add(node.symbol, code);
                return;
            }

            code.Add(false);
            ConvertTreeToTable(code, node.left);
            code.RemoveAt(code.Count - 1);
            code.Add(true);
            ConvertTreeToTable(code, node.right);
        }
Exemplo n.º 7
0
        void InsertNode( int value, HuffmanNode<int> node, int bitsLeft, string bits )
        {
            if( nodeFound ) return;
            if( node.HasValue ) return;

            if( bitsLeft == 0 ) {
                // we cannot add a node if there are further children down the tree
                if( node.Left != null || node.Right != null ) return;
                Console.WriteLine( "ADDED" + value + " : " + bits );
                node.HasValue = true;
                node.Value = value;
                nodeFound = true;
            } else {
                // Keep going down the tree
                if( node.Left == null )
                    node.Left = new HuffmanNode<int>();
                InsertNode( value, node.Left, bitsLeft - 1, bits + "0" );
                if( nodeFound ) return;

                if( node.Right == null )
                    node.Right = new HuffmanNode<int>();
                InsertNode( value, node.Right, bitsLeft - 1, bits + "1" );
            }
        }
Exemplo n.º 8
0
        //3b
        //builds the HuffmanTree so that the left child of each node is a leaf with the highest remaining frequency (growing to the right hand side)
        //NOITCE: the lowest non-leaf node consists of two leafs with the lowest-frequency-leaf (total) as the right child
        public HuffmanNode ReorderTreeToRightSide(HuffmanNode root)
        {
            depthList = new List<List<HuffmanNode>>();
            maximumDepth = 0;
            GoThroughTree(root);

            for (int i = maximumDepth; i > 0; i--)
            {
                depthList[i].Sort((nodeOne, nodeTwo) => nodeOne.depth.CompareTo(nodeTwo.depth));

                while (depthList[i].Count > 0)
                {
                    HuffmanNode newNode = new HuffmanNode(depthList[i][depthList[i].Count - 2], depthList[i][depthList[i].Count - 1]);
                    newNode.depth = newNode.right.depth + 1;
                    depthList[i - 1].Add(newNode);

                    depthList[i].RemoveAt(depthList[i].Count - 1);
                    depthList[i].RemoveAt(depthList[i].Count - 1);
                }
            }

            return depthList[0][0];
        }
Exemplo n.º 9
0
        public void GoThroughTree(HuffmanNode node, int currentDepth = 0)
        {
            if (node.isLeaf)
            {
                node.depth = 0;

                while (depthList.Count <= currentDepth)
                    depthList.Add(new List<HuffmanNode>());

                depthList[currentDepth].Add(node);

                if (currentDepth > maximumDepth)
                    maximumDepth = currentDepth;
            }
            else
            {
                currentDepth++;
                GoThroughTree(node.left, currentDepth);
                GoThroughTree(node.right, currentDepth);
            }
        }
Exemplo n.º 10
0
        //3d
        public void EncodeToPackageMerge(List<HuffmanNode> inputlist, int depth)
        {
            //Sortierung nach Frequenz
            inputlist.Sort((nodeOne, nodeTwo) => nodeOne.frequency.CompareTo(nodeTwo.frequency));
            List<HuffmanNode> nodelist = new List<HuffmanNode>(inputlist);
            //Durchlaufe die Liste entsprechend der Tiefe
            for (int i = 2; i <= depth; i++)
            {
                //Bilde Paare und erstelle einen neuen Knoten, alle erstellten Knoten werden in tempList gespeichert
                List<HuffmanNode> tempList = new List<HuffmanNode>();
                for(int c = 1; c<nodelist.Count; c += 2)
                {
                    HuffmanNode mergedNode = new HuffmanNode(nodelist[c-1].frequency + nodelist[c].frequency, nodelist[c-1], nodelist[c]);
                    tempList.Add(mergedNode);

                }

                nodelist.Clear(); //lösche alte liste
                nodelist.AddRange(inputlist); // setzte liste auf die Anfangswerte
                nodelist.AddRange(tempList); // füge erzeugte knoten der liste hinzu
                tempList.Clear(); //Lösche alte Knoten für einen neuen Schleifendurchlauf

                //Sortiere neue Liste nach frequency
                nodelist.Sort((nodeOne, nodeTwo) => nodeOne.frequency.CompareTo(nodeTwo.frequency));

            }

            //---------------Liste mit Knoten wurde erstellt---------------------------------------------

            var valueTable = new Dictionary<byte, int>();
            for (int i = 0; i<inputlist.Count; i++)
            {
                valueTable[inputlist[i].symbol] = inputlist[i].depth;
            }

            //---------------Liste auf 2n-2 Elemente kürzen-----------------------------------------------

            int cutter = inputlist.Count * 2 - 2;
            if(nodelist.Count > cutter)
                nodelist.RemoveRange(cutter, nodelist.Count-cutter);

            //---------------Key/Value Liste für die Kodierungsgewichtung erstellt------------------------

            for (int i = 0; i < nodelist.Count; i++)
            {

                if (nodelist[i].isDepthNode == true)
                {
                    nodelist.Add(nodelist[i].left);
                    nodelist.Add(nodelist[i].right);
                    nodelist.Remove(nodelist[i]);
                    i--;
                }

                else
                {
                    valueTable[nodelist[i].symbol]++;
                }

            }
            Dictionary<Byte, int> wertOutput = new Dictionary<byte, int>();
            foreach (var item in inputlist)
            {
                wertOutput.Add(item.symbol,item.frequency);
            }
            EncodeToPackageMergeList( valueTable, wertOutput);
        }
Exemplo n.º 11
0
        void InsertNode( int value, HuffmanNode<int> node, int depth )
        {
            if( nodeFound ) return;
            if( node.HasValue ) return;

            if( depth == 0 ) {
                // we cannot add a node if there are further children down the tree
                if( node.Left != null || node.Right != null ) return;

                node.HasValue = true;
                node.Value = value;
                nodeFound = true;
            } else {
                // Keep going down the tree
                if( node.Left == null )
                    node.Left = new HuffmanNode<int>();
                InsertNode( value, node.Left, depth - 1 );
                if( nodeFound ) return;

                if( node.Right == null )
                    node.Right = new HuffmanNode<int>();
                InsertNode( value, node.Right, depth - 1 );
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Recursively traverses Huffman Tree and generates codes
        /// </summary>
        /// <param name="node"></param>
        /// <param name="code"></param>
        private void TraverseHuffmanTree(HuffmanNode node, List<bool> code)
        {
            /* check if both sons are null */
            if (node.Left == node.Right)
            {
                BitArray ba = new BitArray(code.ToArray());
                _huffmanCodes.Add(node.Data, ba);
            }
            else
            {
                /* adds 0 to the code - process left son*/
                code.Add(false);
                TraverseHuffmanTree(node.Left, code);
                code.RemoveAt(code.Count() - 1);

                /* adds 1 to the code - process right son*/
                code.Add(true);
                TraverseHuffmanTree(node.Right, code);
                code.RemoveAt(code.Count() - 1);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Standard implementation of builidng a Huffman Tree
        /// </summary>
        private void BuildHuffmanTree()
        {
            while (_huffmanTree.Count() > 1)
            {
                /* sort Huffman Nodes by frequency */
                _huffmanTree.Sort(CompareNodes);

                HuffmanNode parent = new HuffmanNode(_huffmanTree[0], _huffmanTree[1]);
                _huffmanTree.RemoveAt(0);
                _huffmanTree.RemoveAt(0);
                _huffmanTree.Add(parent);
            }
        }
Exemplo n.º 14
0
        public void HuffmanDepthTest()
        {
            HuffmanNode node1 = new HuffmanNode(1, 1);
            HuffmanNode node2 = new HuffmanNode(2, 1);
            HuffmanNode node3 = new HuffmanNode(5, 5);
            HuffmanNode node4 = new HuffmanNode(7, 7);
            HuffmanNode node5 = new HuffmanNode(10, 10);
            HuffmanNode node6 = new HuffmanNode(14, 14);

            List<HuffmanNode> testList = new List<HuffmanNode> {node1, node5, node3, node6, node2, node4};
            HuffmanEncoder encoder = new HuffmanEncoder();
            Dictionary<byte, int> testDict = new Dictionary<byte, int>();
            //testDict = encoder.EncodeToPackageMerge(testList, 4);
        }
Exemplo n.º 15
0
 /// <summary>
 /// For sorting Huffman Nodes
 /// </summary>
 /// <param name="L1"></param>
 /// <param name="L2"></param>
 /// <returns></returns>
 private static int CompareNodes(HuffmanNode L1, HuffmanNode L2)
 {
     return L1.FrequencyCount.CompareTo(L2.FrequencyCount);
 }
Exemplo n.º 16
0
 public HuffmanNode(char? key, int value, HuffmanNode left = null, HuffmanNode right = null)
 {
     this.Left = left;
     this.Right = right;
     this.Key = key;
     this.Value = value;
 }
Exemplo n.º 17
0
 public HuffmanTree(uint[] leaf_nodes_weight, bool v2 = false)
 {
     var node_list = new List<HuffmanNode> (leaf_nodes_weight.Length * 2);
     uint root_node_weight = 0;
     for (int i = 0; i < leaf_nodes_weight.Length; ++i)
     {
         var node = new HuffmanNode
         {
             Valid = leaf_nodes_weight[i] != 0,
             Weight = leaf_nodes_weight[i],
             IsParent = false
         };
         node_list.Add (node);
         root_node_weight += node.Weight;
     }
     int[] child_node_index = new int[2];
     for (;;)
     {
         uint weight = 0;
         for (int i = 0; i < 2; i++)
         {
             uint min_weight = uint.MaxValue;
             child_node_index[i] = -1;
             int n = 0;
             if (v2)
             {
                 for (; n < node_list.Count; ++n)
                 {
                     if (node_list[n].Valid)
                     {
                         min_weight = node_list[n].Weight;
                         child_node_index[i] = n++;
                         break;
                     }
                 }
                 n = Math.Max (n, i+1);
             }
             for (; n < node_list.Count; ++n)
             {
                 if (node_list[n].Valid && node_list[n].Weight < min_weight)
                 {
                     min_weight = node_list[n].Weight;
                     child_node_index[i] = n;
                 }
             }
             if (-1 == child_node_index[i])
                 continue;
             node_list[child_node_index[i]].Valid = false;
             weight += node_list[child_node_index[i]].Weight;
         }
         var parent_node = new HuffmanNode
         {
             Valid = true,
             IsParent = true,
             LeftChildIndex  = child_node_index[0],
             RightChildIndex = child_node_index[1],
             Weight = weight,
         };
         node_list.Add (parent_node);
         if (weight >= root_node_weight)
             break;
     }
     m_nodes = node_list.ToArray();
 }