public string DecodeBlock(BitArray bits, int indexStart, int indexStop) { string textBlock = ""; //string decoded = ""; NodeHT current = this.Root; for (int i = indexStart; i < indexStop; i++) { if (bits[i]) { if (current.Right != null) { current = current.Right; } } else { if (current.Left != null) { current = current.Left; } } if (IsLeaf(current)) { textBlock += current.Word; current = this.Root; } } return(textBlock); }
public void Decode(BitArray bits, int indexStart, string fileName) { StreamWriter fileWrite = new StreamWriter(@fileName); //string text = ""; NodeHT current = this.Root; string decoded = ""; int endBitArr = bits.Count - 1; while (bits[endBitArr] != true) { endBitArr--; } for (int i = indexStart; i < endBitArr; i++) { if (bits[i]) { if (current.Right != null) { current = current.Right; } } else { if (current.Left != null) { current = current.Left; } } if (IsLeaf(current)) { decoded = current.Word; fileWrite.Write(decoded); //text += decoded; current = this.Root; } } fileWrite.Close(); //File.WriteAllText(fileName, text); }
public void BuildTree(FrequencyDictionary frequencyDictionary) { foreach (KeyValuePair <string, int> word in frequencyDictionary.Dictionary) { nodes.Add(new NodeHT() { Word = word.Key, Frequency = word.Value }); nodesDictionary.Add(word.Key, nodes.Last()); } while (nodes.Count > 1) { List <NodeHT> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList <NodeHT>(); if (orderedNodes.Count >= 2) { // Take first two items List <NodeHT> taken = orderedNodes.Take(2).ToList(); // Create a parent node by combining the frequencies NodeHT parent = new NodeHT() { Word = "", Frequency = taken[0].Frequency + taken[1].Frequency, Left = taken[0], Right = taken[1] }; taken[0].Parent = parent; taken[1].Parent = parent; nodes.Remove(taken[0]); nodes.Remove(taken[1]); nodes.Add(parent); } Root = nodes.FirstOrDefault(); Root.Parent = null; } }
public List <bool> GetCode(NodeHT nodeLeaf) { List <bool> code = new List <bool>(); NodeHT node = nodeLeaf; NodeHT nodePrev = node; while (node != Root) { node = node.Parent; if (node?.Right == nodePrev) { code.Add(true); } if (node?.Left == nodePrev) { code.Add(false); } nodePrev = node; } code?.Reverse(); return(code); }
public bool IsLeaf(NodeHT node) { return(node.Left == null && node.Right == null); }
public HuffmanTree() { nodes = new List <NodeHT>(); Root = null; Frequencies = new FrequencyDictionary(); }