Пример #1
0
        public static Codeword[] PrepareSFCode(double[] Probabilities)
        {
            double[] Probs  = (double[])Probabilities.Clone();
            int[]    Values = new int[Probs.Length];
            for (int i = 0; i < Values.Length; i++)
            {
                Values[i] = i;
            }
            Array.Sort(Probs, Values);

            int[]      Lengths = Probs.Select((x) => (int)Ceiling(-Log(x) / Log(2))).ToArray();
            BigInteger counter = new BigInteger(0);
            int        Clength = Lengths[Lengths.Length - 1];

            Codeword[] CSet = new Codeword[Probabilities.Length];

            for (int i = Lengths.Length - 1; i >= 0; i--)
            {
                if (Lengths[i] > Clength)
                {
                    counter >>= (Clength - Lengths[i]); Clength = Lengths[i];
                }
                CSet[Values[i]] = new Codeword()
                {
                    Length = Clength, CodeWord = GetBits(counter, Clength)
                };
                CSet[Values[i]].CodeWord.Length = Clength;
                counter++;
            }

            return(CSet);
        }
Пример #2
0
        public static Codeword[] PrepareHuffmanCode(double[] Probabilities)
        {
            List <HNode> Roots = new List <HNode>();

            for (int i = 0; i < Probabilities.Length; i++)
            {
                HNode hn = new HNode()
                {
                    Probability = Probabilities[i], LeafNumber = i
                };
                Roots.Add(hn);
            }
            double SmallestProb = Roots[0].Probability;

            while (Roots.Count != 1)
            {
                HNode a = Roots[0];
                HNode b = Roots[1];
                Roots.RemoveRange(0, 2);
                HNode Ha = new HNode()
                {
                    Probability = a.Probability + b.Probability, LeafNumber = -1, Zero = a, One = b
                };
                Roots.Add(Ha);
                Roots.Sort(Ha);
            }
            HNode Rootnode = Roots[0];

            System.Diagnostics.Debug.Assert(Math.Abs(Rootnode.Probability - 1.0) < SmallestProb / 10);

            Codeword[] Result = new Codeword[Probabilities.Length];
            BitArray   BA     = new BitArray(Probabilities.Length);

            GenerateCodewordList(Rootnode, BA, Result, 0);
            return(Result);
        }