public HuffmanNode(HuffmanNode left, HuffmanNode right) { leaf = false; FrequencyCount = left.FrequencyCount + right.FrequencyCount; Left = left; Right = right; }
public Huffman(IEnumerable<KeyValuePair<char, int>> kvps) { //保存原始数据 var tmpOriginalNodes = from kvp in kvps select new HuffmanNode(kvp.Key, kvp.Value); //创建最小优先队列,并输入数据 MinPriorityQueue<HuffmanNode> minQueue = new MinPriorityQueue<HuffmanNode>(); originalNodes = new List<HuffmanNode>(); foreach (var node in tmpOriginalNodes) { originalNodes.Add(node); minQueue.Insert(node); } //建造编码树,并取得编码树的根节点 while (!minQueue.IsEmpty) { HuffmanNode left = minQueue.ExtractMin(); if (minQueue.IsEmpty) { rootNode = left; break; } HuffmanNode right = minQueue.ExtractMin(); HuffmanNode newNode = new HuffmanNode(null, left.Value + right.Value, left, right); left.Parent = newNode; right.Parent = newNode; minQueue.Insert(newNode); } }
void PrintNode( HuffmanNode<int> node, string bits ) { if( node == null ) return; if( node.HasValue ) { Console.WriteLine( node.Value + " : " + bits ); } else { PrintNode( node.Left, "0" + bits ); PrintNode( node.Right, "1" + bits ); } }
private static List<HuffmanNode> createHuffmanNodes(Dictionary<char, int> charFrequency) { var huffmanNodes = new List<HuffmanNode>(capacity: charFrequency.Keys.Count()); foreach (char c in charFrequency.Keys) { var huffmanNode = new HuffmanNode { Characters = c.ToString(), NumOccurrences = charFrequency[c] }; huffmanNodes.Add(huffmanNode); } return huffmanNodes; }
private static void determineHuffmanCodesOfLeafNodes(HuffmanNode node, BitArray shortestBinaryCode) { const bool Zero = false; const bool One = true; if (node.IsLeaf) { node.HuffmanCode = shortestBinaryCode; return; } determineHuffmanCodesOfLeafNodes(node.Left, shortestBinaryCode.WithAppendedValue(Zero)); determineHuffmanCodesOfLeafNodes(node.Right, shortestBinaryCode.WithAppendedValue(One)); }
/// <summary> /// Starts reading 'Bits' array at position 'bitOffset'. Read data is /// used on a Huffman Tree to decode read bits into real strings. /// 'bitOffset' variable is updated with last read bit PLUS ONE (first unread bit). /// </summary> /// <param name="bitOffset"></param> /// <param name="builder"></param> /// <returns> /// decoded string or null if there's an error (last string's bit code is incomplete) /// </returns> /// <remarks> /// Global variables used: /// List(of HuffmanNodes) CharacterTree /// BitArray Bits /// </remarks> private string GetString(ref int bitOffset, StringBuilder builder) { HuffmanNode root = CharacterTree[0]; HuffmanNode curNode = root; builder.Clear(); int i; for (i = bitOffset; i < Bits.Length; i++) { /* reading bits' sequence and decoding it to Strings while traversing Huffman Tree */ int nextNodeID; if (Bits[i]) { nextNodeID = curNode.RightNodeID; } else { nextNodeID = curNode.LeftNodeID; } /* it's an internal node - keep looking for a leaf */ if (nextNodeID >= 0) { curNode = CharacterTree[nextNodeID]; } else /* it's a leaf! */ { char c = (char)(0xffff - nextNodeID); if (c != '\0') { /* it's not NULL */ builder.Append(c); curNode = root; } else { /* it's a NULL terminating processed string, we're done */ bitOffset = i + 1; return(builder.ToString()); } } } bitOffset = i + 1; return(null); }
unsafe public HuffmanTree(bool isCompresser) { loc = new HuffmanNode *[CConstVar.HUFF_MAX + 1]; // for(int i = 0; i < CConstVar.HUFF_MAX+1; i ++){ // loc[i] = new HuffmanNode(); // } blocNode = 0; blocPtrs = 0; nodeList = new HuffmanNode[768]; for (int i = 0; i < 768; i++) { nodeList[i] = new HuffmanNode(); } nodePtrs = new HuffmanNode *[768]; // for(int i = 0; i < 768; i++){ // nodePtrs[i] = new HuffNodePtr(); // } // huffmanMsg.compresser.loc = new HuffmanNode[768]; fixed(HuffmanNode *tmp = &nodeList[blocNode++]) { if (isCompresser) { tree = lhead = loc[CConstVar.HUFF_MAX] = tmp; ltail = null; } else { tree = lhead = ltail = loc[CConstVar.HUFF_MAX] = tmp; } } freeList = null; // freeList = new HuffNodePtr(); tree->symbol = CConstVar.HUFF_MAX; tree->weight = 0; lhead->next = lhead->prev = null; tree->parent = tree->left = tree->right = null; if (isCompresser) { loc[CConstVar.HUFF_MAX] = tree; } }
// Setting the codes of the nodes of tree. Recursive method. private static void setCodeToTheTree(string code, HuffmanNode root) { if (root == null) { return; } if (root.child[0] == null && root.child[1] == null) { root.currentCode = code; root.w.code = code; return; } setCodeToTheTree(code + "0", root.child[0]); setCodeToTheTree(code + "1", root.child[1]); }
public static void Main() { var node5 = new HuffmanNode(5, ' '); var node2 = new HuffmanNode(2, ' '); var node3a = new HuffmanNode(3, 'a'); var node1b = new HuffmanNode(1, 'b'); var node1c = new HuffmanNode(1, 'c'); node5.left = node2; node5.right = node3a; node2.left = node1b; node2.right = node1c; var result = DecodeIterative("1001011", node5); var resultRecursive = DecodeRecursive("1001011", node5); }
private void GenerarListaNodosHoja(HuffmanNode raiz) { if (raiz == null) { return; } else if (raiz.isLeaf) { ListaHojas.Add(raiz); return; } GenerarListaNodosHoja(raiz.leftTree); GenerarListaNodosHoja(raiz.rightTree); }
/// <summary> /// Adds a child in direction `newdirection` to the tree and gives the child /// the value `newvalue`. If `newvalue` is set between 0x0000 and 0xfffe the /// child is seen as an endnode, if 0xffff the child is just another node with /// two children /// </summary> protected void AddNewChildToHuffmanNode(ref HuffmanNode HuffmanNode, byte newdirection, int newvalue) { HuffmanNode newnode = new HuffmanNode() { value = newvalue, next = new HuffmanNode[] { null, null }, endnode = new bool[] { false, false }, }; if (newvalue < 0xffff) { HuffmanNode.endnode[newdirection] = true; } HuffmanNode.next[newdirection] = newnode; }
// //recurses through the entire tree and stacks up the respective code, then adds the respective symbol and code to the HuffmanTable when reaching a leave public void ConvertTreeToTable(List<bool> code, HuffmanNode node) { if (node == null) return; if (node.isLeaf == true) { huffmanTable.Add(node.symbol, code); return; } code.Add(false); ConvertTreeToTable(code, node.left); code.RemoveAt(code.Count - 1); code.Add(true); ConvertTreeToTable(code, node.right); }
public static string DecodeIterative(string s, HuffmanNode root) { StringBuilder sb = new StringBuilder(); HuffmanNode c = root; for (int i = 0; i < s.Length; i++) { c = s[i] == '1' ? c.right : c.left; if (c.left == null && c.right == null) { sb.Append(c.data); c = root; } } return(sb.ToString()); }
/// <summary> /// Starts reading 'Bits' array at position 'bitOffset'. Read data is /// used on a Huffman Tree to decode read bits into real strings. /// 'bitOffset' variable is updated with last read bit PLUS ONE (first unread bit). /// </summary> /// <param name="bitOffset"></param> /// <returns> /// decoded string or null if there's an error (last string's bit code is incomplete) /// </returns> /// <remarks> /// Global variables used: /// List(of HuffmanNodes) CharacterTree /// BitArray Bits /// </remarks> private string GetString(ref int bitOffset) { HuffmanNode root = CharacterTree[0]; HuffmanNode curNode = root; string curString = ""; int i; for (i = bitOffset; i < Bits.Length; i++) { /* reading bits' sequence and decoding it to Strings while traversing Huffman Tree */ int nextNodeID; if (Bits[i]) { nextNodeID = curNode.RightNodeID; } else { nextNodeID = curNode.LeftNodeID; } /* it's an internal node - keep looking for a leaf */ if (nextNodeID >= 0) { curNode = CharacterTree[nextNodeID]; } else /* it's a leaf! */ { char c = BitConverter.ToChar(BitConverter.GetBytes(0xffff - nextNodeID), 0); if (c != '\0') { /* it's not NULL */ curString += c; curNode = root; } else { /* it's a NULL terminating processed string, we're done */ bitOffset = i + 1; return(curString); } } } bitOffset = i + 1; return(null); }
private void drawLines(HuffmanNode node) { if (node.leftNode != null) { Line line = new Line() { X1 = node.xCord + 25, Y1 = node.yCord + 25, X2 = node.leftNode.xCord + 25, Y2 = node.leftNode.yCord + 25, Stroke = new SolidColorBrush((Color)Application.Current.Resources["SystemAccentColorLight3"]), StrokeThickness = 1, }; resultGrid.Children.Add(line); TextBlock textBlock = new TextBlock() { Text = "0" }; resultGrid.Children.Add(textBlock); Canvas.SetLeft(textBlock, ((line.X1 + line.X2) / 2) - 10); Canvas.SetTop(textBlock, ((line.Y1 + line.Y2) / 2) - 25); Canvas.SetZIndex(line, -1); drawLines(node.leftNode); } if (node.rightNode != null) { Line line = new Line() { X1 = node.xCord + 25, Y1 = node.yCord + 25, X2 = node.rightNode.xCord + 25, Y2 = node.rightNode.yCord + 25, Stroke = new SolidColorBrush((Color)Application.Current.Resources["SystemAccentColorLight3"]), StrokeThickness = 1, }; resultGrid.Children.Add(line); TextBlock textBlock = new TextBlock() { Text = "1" }; resultGrid.Children.Add(textBlock); Canvas.SetLeft(textBlock, ((line.X1 + line.X2) / 2) + 10); Canvas.SetTop(textBlock, ((line.Y1 + line.Y2) / 2) - 25); Canvas.SetZIndex(line, -1); drawLines(node.rightNode); } }
private void HUF_CreateCodeWorks() { byte[] scode = new byte[100]; uint i; for (i = 0; i < num_leafs; i++) { HuffmanNode node = tree[i]; uint symbol = node.symbol; uint nbits = 0; while (node.dad != null) { scode[nbits++] = node.dad.lson == node ? (byte)HUF_LNODE : (byte)HUF_RNODE; node = node.dad; } uint maxbytes = (nbits + 7) >> 3; HuffmanCode code = new HuffmanCode(); codes[symbol] = code; code.nbits = nbits; code.codework = new byte[maxbytes]; uint j; for (j = 0; j < maxbytes; j++) { code.codework[j] = 0; } byte mask = (byte)HUF_MASK; j = 0; uint nbit; for (nbit = nbits; nbit != 0; nbit--) { if (scode[nbit - 1] != 0) { code.codework[j] |= mask; } if ((mask >>= HUF_SHIFT) == 0) { mask = (byte)HUF_MASK; j++; } } } }
private int BuildTree(HuffmanNode node, int index) { if (index >= _huffmanTree.Length) { return(-1); } var branchDescription = _huffmanTree[index]; index += 1; node.Childs = new HuffmanNode[2]; for (var i = 0; i < node.Childs.Length; i++) { node.Childs[i] = new HuffmanNode { Value = -1, Code = new List <Bit>(node.Code) }; node.Childs[i].Code.Add(i); if ((branchDescription & (1 << i)) == 0) { index = BuildTree(node.Childs[i], index); if (index < 0) { return(-1); } continue; } if (index >= _huffmanTree.Length) { return(-1); } node.Childs[i].Value = _huffmanTree[index]; node.Childs[i].Childs = null; _codeTable[node.Childs[i].Value] = node.Childs[i]; index += 1; } return(index); }
private string GetString(int bitOffset) { HuffmanNode root = nodes[0]; HuffmanNode curNode = root; string curString = ""; int i; for (i = bitOffset; i < Bits.Length; i++) { /* reading bits' sequence and decoding it to Strings while traversing Huffman Tree */ int nextNodeID; if (Bits[i]) { nextNodeID = curNode.RightNodeID; } else { nextNodeID = curNode.LeftNodeID; } /* it's an internal node - keep looking for a leaf */ if (nextNodeID >= 0) { curNode = nodes[nextNodeID]; } else /* it's a leaf! */ { char c = curNode.data; if (c != '\0') { /* it's not NULL */ curString += c; curNode = root; i--; } else { /* it's a NULL terminating processed string, we're done */ //skip ahead approximately 9 bytes to the next string return(curString); } } } return(null); }
private static HuffmanNode _ConstructHuffmanTree(BitArray bitArray, ref int I) { HuffmanNode curr = new HuffmanNode(); curr.Size = 1; if (bitArray[I] == true) { return(curr); } I++; curr.Left = _ConstructHuffmanTree(bitArray, ref I); curr.Size += curr.Left.Size; I++; curr.Right = _ConstructHuffmanTree(bitArray, ref I); curr.Size += curr.Right.Size; return(curr); }
public static char FindCharacter(string s, HuffmanNode node) { if (node.data != ' ') { return(node.data); } if (s[index] == '1') { index++; return(FindCharacter(s, node.right)); } else { index++; return(FindCharacter(s, node.left)); } }
public void Build(string source) { // Find the characters and its frequencies for (int i = 0; i < source.Length; i++) { if (!Frequencies.ContainsKey(source[i])) { Frequencies.Add(source[i], 0); } Frequencies[source[i]]++; } // add the char and its frequencies like nodes in nodes foreach (KeyValuePair <char, int> keyValuePair in Frequencies) { nodes.Add(new HuffmanNode() { Symbol = keyValuePair.Key, Frequency = keyValuePair.Value }); } while (nodes.Count > 1) { // need to arrange in ascending order before build the tree. List <HuffmanNode> orderedNodes = nodes.OrderBy(o => o.Frequency).ToList <HuffmanNode>(); if (orderedNodes.Count >= 2) { List <HuffmanNode> taken = orderedNodes.Take(2).ToList <HuffmanNode>(); HuffmanNode parent = new HuffmanNode() { Left = taken[0], Right = taken[1], Symbol = '*', Frequency = taken[0].Frequency + taken[1].Frequency }; nodes.Remove(taken[0]); nodes.Remove(taken[1]); nodes.Add(parent); } this.Root = nodes.FirstOrDefault(); } }
/// <summary> /// Decodes a given binary path to represent it's string value /// </summary> /// <param name="bits">BitArray for traversing the tree</param> /// <returns></returns> public string Decode(BitArray bits) { HuffmanNode current = Root; string decodedString = string.Empty; foreach (bool bit in bits) { //Find the correct current node depending on the bit set or not set. current = (bit ? current.Right ?? current : current.Left ?? current); if (current.IsLeaf()) { decodedString += current.Character; current = Root; } } return(decodedString); }
private HuffmanNode AsignarCodigosPrefijo(string codigoprefijo, HuffmanNode hnNodoActual) { if (hnNodoActual == null) { return(null); } else if (hnNodoActual.leftTree == null && hnNodoActual.rightTree == null) { hnNodoActual.code = codigoprefijo; return(hnNodoActual); } hnNodoActual.leftTree = AsignarCodigosPrefijo(codigoprefijo + "0", hnNodoActual.leftTree); hnNodoActual.rightTree = AsignarCodigosPrefijo(codigoprefijo + "1", hnNodoActual.rightTree); return(hnNodoActual); }
/// <summary> /// Converts a Huffman Tree to it's binary representation used by TLK format of Mass Effect 2. /// </summary> /// <returns></returns> private List <int> ConvertHuffmanTreeToBuffer() { Queue <HuffmanNode> q = new Queue <HuffmanNode>(); Dictionary <int, HuffmanNode> indices = new Dictionary <int, HuffmanNode>(); int index = 0; q.Enqueue(_huffmanTree[0]); while (q.Count > 0) { HuffmanNode node = q.Dequeue(); /* if it's a leaf - set it's ID to reflect char data the node contains */ if (node.Left == node.Right) { /* store the char data */ node.ID = -1 - node.Data; /* that's how it's going to be decoded when parsing TLK file: * char c = BitConverter.ToChar(BitConverter.GetBytes(0xffff - node.ID), 0); */ } else { node.ID = index++; indices.Add(node.ID, node); } if (node.Right != null) { q.Enqueue(node.Right); } if (node.Left != null) { q.Enqueue(node.Left); } } List <int> output = new List <int>(); foreach (HuffmanNode node in indices.Values) { output.Add(node.Left.ID); output.Add(node.Right.ID); } return(output); }
/// <summary> /// Converts a Huffman Tree to it's binary representation used by TLK format of Mass Effect 1. /// </summary> /// <returns></returns> private byte[] ConvertHuffmanTreeToBuffer() { List <HuffmanNode> nodes = new List <HuffmanNode>(); Queue <HuffmanNode> q = new Queue <HuffmanNode>(); ushort index = 0; q.Enqueue(_huffmanTree[0]); while (q.Count > 0) { HuffmanNode node = q.Dequeue(); nodes.Add(node); node.ID = index; index++; if (node.Right != null) { q.Enqueue(node.Right); } if (node.Left != null) { q.Enqueue(node.Left); } } List <byte> output = new List <byte>(); output.AddRange(BitConverter.GetBytes((int)index)); foreach (HuffmanNode node in nodes) { if (node.leaf) { output.Add(1); output.AddRange(BitConverter.GetBytes(node.Data)); } else { output.Add(0); output.AddRange(BitConverter.GetBytes(node.Right.ID)); output.AddRange(BitConverter.GetBytes(node.Left.ID)); } } return(output.ToArray()); }
private static void _ConstuctHuffmanTable(HuffmanNode Node, int Depth, BitArray Code, BitArray[] Table) { if (Node.IsLeaf()) { Table[Node.Value] = new BitArray(Depth); for (int i = 0; i < Depth; i++) { bool b = Code.Get(i); Table[Node.Value].Set(i, b); } return; } Code.Set(Depth, false); _ConstuctHuffmanTable(Node.Left, Depth + 1, Code, Table); Code.Set(Depth, true); _ConstuctHuffmanTable(Node.Right, Depth + 1, Code, Table); }
private string ProcessNode(HuffmanNode node) { var innerHtml = node.Character == '\0' ? NodeTemplate.Replace("{frequency}", node.Frequency.ToString()) : LeafTemplate.Replace("{frequency}", node.Frequency.ToString()) .Replace("{character}", char.IsWhiteSpace(node.Character) ? "' '" : node.Character.ToString()) .Replace("{path}", _tree.GetPath(node.Character)); innerHtml = innerHtml.Replace("{left}", node.Left != null ? ProcessNode(node.Left) : string.Empty); innerHtml = innerHtml.Replace("{right}", node.Right != null ? ProcessNode(node.Right) : string.Empty); return(innerHtml); }
public void Build(IEnumerable <CharacterFrequency> input) { var queue = new PriorityQueue <HuffmanNode, int>(); var frequencies = input.ToList(); _nodes = new HuffmanNode[frequencies.Count]; var count = 0; foreach (var item in frequencies) { var node = new HuffmanNode { Frequency = item.Frequency, Character = item.Character }; queue.Add(node); _nodes[count] = node; count++; } while (queue.Length > 1) { var left = queue.PopMin(); var right = queue.PopMin(); var node = new HuffmanNode { Frequency = left.Frequency + right.Frequency, Left = left, Right = right }; left.Parent = node; right.Parent = node; queue.Add(node); } Root = queue.PopMin(); }
static HuffmanCompressor() { var assembly = Assembly.GetExecutingAssembly(); var serializer = new JsonSerializer(); string assemblyTitle = assembly.GetCustomAttribute <AssemblyTitleAttribute>().Title; var resourceName = assemblyTitle + ".english-huffman.json"; using (var stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(reader)) { var packed = (JObject)serializer.Deserialize(jsonReader); foreach (var prop in packed.Properties()) { var prefix = prop.Name; Trees[prefix] = new HuffmanNode(); var treespec = (string)((JValue)prop.Value).Value; var path = new List <char>(30); for (int i = 0; i < treespec.Length; i += 2) { char ch = treespec[i]; int zeroes = "0123456789abcdefghijklmnop".IndexOf(treespec[i + 1]); if (i != 0) { int idx = path.Count - 1; while (path[idx] == '1') { idx--; } path.RemoveRange(idx + 1, path.Count - idx - 1); path[idx] = '1'; } path.AddRange(Enumerable.Repeat('0', zeroes)); Trees[prefix].Populate(path, ch); } } } }
/// <summary> /// 获取哈夫曼字符编码对照表. /// </summary> /// <param name="huffmanNode"></param> /// <returns></returns> public Dictionary <char, BitArray> GetHuffmanCode(List <HuffmanNode> huffmanNode) { Dictionary <char, BitArray> huffmanCode = new Dictionary <char, BitArray>(); foreach (HuffmanNode oneNode in huffmanNode.Where(p => p.CharValue != 0)) { List <bool> values = new List <bool>(); HuffmanNode currentNode = oneNode; while (currentNode.Parent != null) { if (currentNode.Parent.LeftChild == currentNode) { values.Add(false); } else//1 { values.Add(true); } currentNode = currentNode.Parent; } values.Reverse(); huffmanCode.Add(oneNode.CharValue, new BitArray(values.ToArray())); } foreach (char key in huffmanCode.Keys) { Console.Write("{0} : ", key); foreach (bool bit in huffmanCode[key]) { Console.Write(bit ? '1' : '0'); } Console.WriteLine(); } return(huffmanCode); }
public static byte[] Decode(byte[] input) { BitArray bitArray = new BitArray(input); HuffmanNode root = ConstructHuffmanTree(bitArray); int header1Size = root.Size; int currBytePosition = BitLengthToByteLength(header1Size); int header2Size = ConstructHuffmanTreeLeaves(root, input, currBytePosition); currBytePosition += header2Size; int codeLength = ByteArrToInt(input, currBytePosition); currBytePosition += 4; List <Byte> decodedOutput = new List <byte>(); int currBitPosition = currBytePosition * 8; HuffmanNode currNode; int c = 0; while (currBitPosition < bitArray.Length && c < codeLength) { currNode = root; while (!currNode.IsLeaf()) { bool b = bitArray[currBitPosition++]; c++; if (b) { currNode = currNode.Right; } else { currNode = currNode.Left; } } decodedOutput.Add(currNode.Value); } return(decodedOutput.ToArray()); }
private void calculate(object sender, RoutedEventArgs e) { List <HuffmanNode> nodeList = getList(); HuffmanCoding huffmanCoding = new HuffmanCoding(); huffmanCoding.getTreeFromList(nodeList); huffmanCoding.setCodeToTheTree("", nodeList[0]); while (nodeList.Count > 1) { HuffmanNode node1 = nodeList[0]; nodeList.RemoveAt(0); HuffmanNode node2 = nodeList[0]; nodeList.RemoveAt(0); nodeList.Add(new HuffmanNode(node1, node2)); nodeList.Sort(); } resultGrid.Children.Clear(); i = 0; showTree(0, nodeList[0]); resultGrid.Width = i * 50; drawLines(nodeList[0]); treeScrollViewer.Visibility = Visibility.Visible; treeScrollViewer.Opacity = 0; treeScrollViewer.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; treeScrollViewer.Opacity = 1; codingTable.Visibility = Visibility.Visible; codingTable.Opacity = 0; codingTable.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; codingTable.Opacity = 1; codingTable.Children.Clear(); showCodeInList(nodeList[0]); }
public void GenerarArbol(List <HuffmanNode> ListaCaracteres) { while (ListaCaracteres.Count > 1) { ListaCaracteres.Sort(); HuffmanNode hnDerecho = ListaCaracteres[0]; ListaCaracteres.RemoveAt(0); HuffmanNode hnIzquierdo = ListaCaracteres[0]; ListaCaracteres.RemoveAt(0); HuffmanNode nAux = new HuffmanNode(); nAux = nAux.CrearNodoPadre(hnDerecho, hnIzquierdo); nAux.rightTree.parentNode = nAux; nAux.leftTree.parentNode = nAux; ListaCaracteres.Add(nAux); } hnRaiz = AsignarCodigosPrefijo("", ListaCaracteres[0]); GenerarListaNodosHoja(hnRaiz); }
private void TraverseHuffmanTree(HuffmanNode node, List <bool> code) { /* check if both sons are null */ if (node.Left == node.Right) { var ba = new BitArray(code.ToArray()); _huffmanCodes.Add(node.Value, ba); } else { /* adds 0 to the code - process left son*/ code.Add(false); TraverseHuffmanTree(node.Left, code); code.RemoveAt(code.Count() - 1); /* adds 1 to the code - process right son*/ code.Add(true); TraverseHuffmanTree(node.Right, code); code.RemoveAt(code.Count() - 1); } }
/// <summary> /// Builds the Huffman tree /// </summary> /// <param name="source">The source to build the Hufftree from</param> /// <exception cref="ArgumentNullException">Thrown when source is null or empty</exception> public void BuildTree(string source) { nodes.Clear(); //As we build a new tree, first make sure it's clean :) if (string.IsNullOrEmpty(source)) { throw new ArgumentNullException("source"); } else { Frequencies.Accept(source); foreach (KeyValuePair <char, int> symbol in Frequencies.FrequencyTable) { nodes.Add(new HuffmanNode() { Character = symbol.Key, Frequency = symbol.Value }); } while (nodes.Count > 1) { List <HuffmanNode> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList(); if (orderedNodes.Count >= 2) { List <HuffmanNode> takenNodes = orderedNodes.Take(2).ToList(); HuffmanNode parent = new HuffmanNode() { Character = null, Frequency = takenNodes[0].Frequency + takenNodes[1].Frequency, Left = takenNodes[0], Right = takenNodes[1] }; //Remove the childnodes from the original node list and add the new parent node nodes.Remove(takenNodes[0]); nodes.Remove(takenNodes[1]); nodes.Add(parent); } } Root = nodes.FirstOrDefault(); } }
public void FindCoef(string EncodedData) { while (EncodedData.Length > 0) { if (currentNode.left == null && currentNode.right == null) { return; } string temp = EncodedData.Substring(0, 1); EncodedData = EncodedData.Substring(1); if (temp == "0") { HuffmanNode tempNode = currentNode; currentNode = tempNode.left; } else if (temp == "1") { HuffmanNode tempNode = currentNode; currentNode = tempNode.right; } } }
void InsertNode( int value, HuffmanNode<int> node, int bitsLeft, string bits ) { if( nodeFound ) return; if( node.HasValue ) return; if( bitsLeft == 0 ) { // we cannot add a node if there are further children down the tree if( node.Left != null || node.Right != null ) return; Console.WriteLine( "ADDED" + value + " : " + bits ); node.HasValue = true; node.Value = value; nodeFound = true; } else { // Keep going down the tree if( node.Left == null ) node.Left = new HuffmanNode<int>(); InsertNode( value, node.Left, bitsLeft - 1, bits + "0" ); if( nodeFound ) return; if( node.Right == null ) node.Right = new HuffmanNode<int>(); InsertNode( value, node.Right, bitsLeft - 1, bits + "1" ); } }
/// <summary> /// Standard implementation of builidng a Huffman Tree /// </summary> private void BuildHuffmanTree() { while (_huffmanTree.Count() > 1) { /* sort Huffman Nodes by frequency */ _huffmanTree.Sort(CompareNodes); HuffmanNode parent = new HuffmanNode(_huffmanTree[0], _huffmanTree[1]); _huffmanTree.RemoveAt(0); _huffmanTree.RemoveAt(0); _huffmanTree.Add(parent); } }
public void HuffmanDepthTest() { HuffmanNode node1 = new HuffmanNode(1, 1); HuffmanNode node2 = new HuffmanNode(2, 1); HuffmanNode node3 = new HuffmanNode(5, 5); HuffmanNode node4 = new HuffmanNode(7, 7); HuffmanNode node5 = new HuffmanNode(10, 10); HuffmanNode node6 = new HuffmanNode(14, 14); List<HuffmanNode> testList = new List<HuffmanNode> {node1, node5, node3, node6, node2, node4}; HuffmanEncoder encoder = new HuffmanEncoder(); Dictionary<byte, int> testDict = new Dictionary<byte, int>(); //testDict = encoder.EncodeToPackageMerge(testList, 4); }
public HuffmanNode(char? key, int value, HuffmanNode left = null, HuffmanNode right = null) { this.Left = left; this.Right = right; this.Key = key; this.Value = value; }
void InsertNode( int value, HuffmanNode<int> node, int depth ) { if( nodeFound ) return; if( node.HasValue ) return; if( depth == 0 ) { // we cannot add a node if there are further children down the tree if( node.Left != null || node.Right != null ) return; node.HasValue = true; node.Value = value; nodeFound = true; } else { // Keep going down the tree if( node.Left == null ) node.Left = new HuffmanNode<int>(); InsertNode( value, node.Left, depth - 1 ); if( nodeFound ) return; if( node.Right == null ) node.Right = new HuffmanNode<int>(); InsertNode( value, node.Right, depth - 1 ); } }
/// <summary> /// For sorting Huffman Nodes /// </summary> /// <param name="L1"></param> /// <param name="L2"></param> /// <returns></returns> private static int CompareNodes(HuffmanNode L1, HuffmanNode L2) { return L1.FrequencyCount.CompareTo(L2.FrequencyCount); }
//3d public void EncodeToPackageMerge(List<HuffmanNode> inputlist, int depth) { //Sortierung nach Frequenz inputlist.Sort((nodeOne, nodeTwo) => nodeOne.frequency.CompareTo(nodeTwo.frequency)); List<HuffmanNode> nodelist = new List<HuffmanNode>(inputlist); //Durchlaufe die Liste entsprechend der Tiefe for (int i = 2; i <= depth; i++) { //Bilde Paare und erstelle einen neuen Knoten, alle erstellten Knoten werden in tempList gespeichert List<HuffmanNode> tempList = new List<HuffmanNode>(); for(int c = 1; c<nodelist.Count; c += 2) { HuffmanNode mergedNode = new HuffmanNode(nodelist[c-1].frequency + nodelist[c].frequency, nodelist[c-1], nodelist[c]); tempList.Add(mergedNode); } nodelist.Clear(); //lösche alte liste nodelist.AddRange(inputlist); // setzte liste auf die Anfangswerte nodelist.AddRange(tempList); // füge erzeugte knoten der liste hinzu tempList.Clear(); //Lösche alte Knoten für einen neuen Schleifendurchlauf //Sortiere neue Liste nach frequency nodelist.Sort((nodeOne, nodeTwo) => nodeOne.frequency.CompareTo(nodeTwo.frequency)); } //---------------Liste mit Knoten wurde erstellt--------------------------------------------- var valueTable = new Dictionary<byte, int>(); for (int i = 0; i<inputlist.Count; i++) { valueTable[inputlist[i].symbol] = inputlist[i].depth; } //---------------Liste auf 2n-2 Elemente kürzen----------------------------------------------- int cutter = inputlist.Count * 2 - 2; if(nodelist.Count > cutter) nodelist.RemoveRange(cutter, nodelist.Count-cutter); //---------------Key/Value Liste für die Kodierungsgewichtung erstellt------------------------ for (int i = 0; i < nodelist.Count; i++) { if (nodelist[i].isDepthNode == true) { nodelist.Add(nodelist[i].left); nodelist.Add(nodelist[i].right); nodelist.Remove(nodelist[i]); i--; } else { valueTable[nodelist[i].symbol]++; } } Dictionary<Byte, int> wertOutput = new Dictionary<byte, int>(); foreach (var item in inputlist) { wertOutput.Add(item.symbol,item.frequency); } EncodeToPackageMergeList( valueTable, wertOutput); }
public void GoThroughTree(HuffmanNode node, int currentDepth = 0) { if (node.isLeaf) { node.depth = 0; while (depthList.Count <= currentDepth) depthList.Add(new List<HuffmanNode>()); depthList[currentDepth].Add(node); if (currentDepth > maximumDepth) maximumDepth = currentDepth; } else { currentDepth++; GoThroughTree(node.left, currentDepth); GoThroughTree(node.right, currentDepth); } }
//3b //builds the HuffmanTree so that the left child of each node is a leaf with the highest remaining frequency (growing to the right hand side) //NOITCE: the lowest non-leaf node consists of two leafs with the lowest-frequency-leaf (total) as the right child public HuffmanNode ReorderTreeToRightSide(HuffmanNode root) { depthList = new List<List<HuffmanNode>>(); maximumDepth = 0; GoThroughTree(root); for (int i = maximumDepth; i > 0; i--) { depthList[i].Sort((nodeOne, nodeTwo) => nodeOne.depth.CompareTo(nodeTwo.depth)); while (depthList[i].Count > 0) { HuffmanNode newNode = new HuffmanNode(depthList[i][depthList[i].Count - 2], depthList[i][depthList[i].Count - 1]); newNode.depth = newNode.right.depth + 1; depthList[i - 1].Add(newNode); depthList[i].RemoveAt(depthList[i].Count - 1); depthList[i].RemoveAt(depthList[i].Count - 1); } } return depthList[0][0]; }
/// <summary> /// Recursively traverses Huffman Tree and generates codes /// </summary> /// <param name="node"></param> /// <param name="code"></param> private void TraverseHuffmanTree(HuffmanNode node, List<bool> code) { /* check if both sons are null */ if (node.Left == node.Right) { BitArray ba = new BitArray(code.ToArray()); _huffmanCodes.Add(node.Data, ba); } else { /* adds 0 to the code - process left son*/ code.Add(false); TraverseHuffmanTree(node.Left, code); code.RemoveAt(code.Count() - 1); /* adds 1 to the code - process right son*/ code.Add(true); TraverseHuffmanTree(node.Right, code); code.RemoveAt(code.Count() - 1); } }
public HuffmanTree(uint[] leaf_nodes_weight, bool v2 = false) { var node_list = new List<HuffmanNode> (leaf_nodes_weight.Length * 2); uint root_node_weight = 0; for (int i = 0; i < leaf_nodes_weight.Length; ++i) { var node = new HuffmanNode { Valid = leaf_nodes_weight[i] != 0, Weight = leaf_nodes_weight[i], IsParent = false }; node_list.Add (node); root_node_weight += node.Weight; } int[] child_node_index = new int[2]; for (;;) { uint weight = 0; for (int i = 0; i < 2; i++) { uint min_weight = uint.MaxValue; child_node_index[i] = -1; int n = 0; if (v2) { for (; n < node_list.Count; ++n) { if (node_list[n].Valid) { min_weight = node_list[n].Weight; child_node_index[i] = n++; break; } } n = Math.Max (n, i+1); } for (; n < node_list.Count; ++n) { if (node_list[n].Valid && node_list[n].Weight < min_weight) { min_weight = node_list[n].Weight; child_node_index[i] = n; } } if (-1 == child_node_index[i]) continue; node_list[child_node_index[i]].Valid = false; weight += node_list[child_node_index[i]].Weight; } var parent_node = new HuffmanNode { Valid = true, IsParent = true, LeftChildIndex = child_node_index[0], RightChildIndex = child_node_index[1], Weight = weight, }; node_list.Add (parent_node); if (weight >= root_node_weight) break; } m_nodes = node_list.ToArray(); }