Ejemplo n.º 1
0
        public static HuffmanTree2 Create(string file)
        {
            var tree = new HuffmanTree2();
            var path = file.Substring(file.Length - 4) + "_huffman.txt";

            if (File.Exists(path))
            {
                tree.LoadTxt(path);
            }
            else
            {
                tree.Encode(HuffmanNodeList.Create(file));
                tree.Save2Txt(file);
            }
            return(tree);
        }
Ejemplo n.º 2
0
        public void Encode(HuffmanNodeList hnl)
        {
            while (hnl.Count > 1)
            {
                var arr   = hnl.PopTwo();
                var left  = arr[0];
                var right = arr[1];
                left.PathCode  = 0;
                right.PathCode = 1;
                var parent = new HuffmanNode(left.Freq + right.Freq, left, right);
                left.Parent  = parent;
                right.Parent = parent;
                hnl.Add(parent);
            }
            Root = hnl.GetFirst();

            for (int i = 0; i < hnl.Leaves.Length; i++)
            {
                var node = hnl.Leaves[i];
                var key  = node.Word;
                var cs   = new List <char>();
                while (node.Parent != null)
                {
                    cs.Add(node.PathCode == 0 ? '0' : '1');
                    node = node.Parent;
                }
                var chars = new char[cs.Count];
                for (int j = cs.Count - 1; j >= 0; j--)
                {
                    chars[cs.Count - 1 - j] = cs[j];
                }
                var code = new string(chars);
                table[key]    = code;
                reTable[code] = key;
            }
        }