示例#1
0
        public string Decode(BitArray bits)
        {
            Nodee  current = this.Root;
            string decoded = "";

            foreach (bool bit in bits)
            {
                if (bit)
                {
                    if (current.Right != null)
                    {
                        current = current.Right;
                    }
                }
                else
                {
                    if (current.Left != null)
                    {
                        current = current.Left;
                    }
                }

                if (IsLeaf(current))
                {
                    decoded += current.Symbol;
                    current  = this.Root;
                }
            }

            return(decoded);
        }
示例#2
0
        public void Build(string source)
        {
            for (int i = 0; i < source.Length; i++)
            {
                if (!Frequencies.ContainsKey(source[i]))
                {
                    Frequencies.Add(source[i], 0);
                }

                Frequencies[source[i]]++;
            }

            foreach (KeyValuePair <char, int> symbol in Frequencies)
            {
                nodes.Add(new Nodee()
                {
                    Symbol = symbol.Key, Frequency = symbol.Value
                });
            }

            while (nodes.Count > 1)
            {
                List <Nodee> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList <Nodee>();

                if (orderedNodes.Count >= 2)
                {
                    // Take first two items
                    List <Nodee> taken = orderedNodes.Take(2).ToList <Nodee>();

                    // Create a parent node by combining the frequencies
                    Nodee parent = new Nodee()
                    {
                        Symbol    = '*',
                        Frequency = taken[0].Frequency + taken[1].Frequency,
                        Left      = taken[0],
                        Right     = taken[1]
                    };

                    nodes.Remove(taken[0]);
                    nodes.Remove(taken[1]);
                    nodes.Add(parent);
                }

                this.Root = nodes.FirstOrDefault();
            }
        }
示例#3
0
 public bool IsLeaf(Nodee node)
 {
     return(node.Left == null && node.Right == null);
 }