/// <summary> /// For any symbol looks over the binary tree and makes a encoding - binary string representation /// </summary> /// <param name="key">HuffmanNode</param> /// <exception cref="ArgumentException"></exception> private List <int> Encode(HuffmanNode <T> key) { var encoding = new List <int>(); var tempNode = key; while (!tempNode.IsRoot) { encoding.Add(tempNode.Bit); tempNode = tempNode.Parent; } encoding.Reverse(); return(encoding); }
public T Decode(List <int> bitString, ref int position) { HuffmanNode <T> nodeCur = _root; while (!nodeCur.IsLeaf) { if (position > bitString.Count) { throw new ArgumentException("Invalid bitstring in Decode"); } nodeCur = bitString[position++] == 0 ? nodeCur.LeftSon : nodeCur.RightSon; } return(nodeCur.Value); }
public void Encode(T value, List <int> encoding) { if (!_leafDictionary.ContainsKey(value)) { throw new ArgumentException("Invalid value in Encode"); } HuffmanNode <T> nodeCur = _leafDictionary[value]; var reverseEncoding = new List <int>(); while (!nodeCur.IsRoot) { reverseEncoding.Add(nodeCur.Bit); nodeCur = nodeCur.Parent; } reverseEncoding.Reverse(); encoding.AddRange(reverseEncoding); }
/// <summary> /// Huffman Coding - Building a binary tree that will encode symbols /// </summary> /// <param name="values">A bunch of data of type T</param> public void Huffman(IEnumerable <T> values) { //store symbols and their quantity in the text var quant_Dict = Count_Symbols(values); //init a min-heap that stores HuffmanNodes var priorityQueue = Get_Queue(quant_Dict); while (priorityQueue.Count > 1) { HuffmanNode <T> leftSon = priorityQueue.ExtractMin(); HuffmanNode <T> rightSon = priorityQueue.ExtractMin(); var parent = new HuffmanNode <T>(leftSon, rightSon); priorityQueue.Add(parent); } _root = priorityQueue.ExtractMin(); _root.IsZero = false; }