1

I try to implement Huffman encoding compression algorithm. The Encode function works for me but when i use decode function didn't give me a right result. I write the output from encoding function in text file and read it to pass to decode function when i try to solve the same problem with myself the result different from the algorithm code result, what's is the wrong ? this is my encode function

public static void GenerateCode(Node parentNode, string code)
{
  if (parentNode != null)
  {
    GenerateCode(parentNode.leftChild, code + "0");

    if (parentNode.leftChild == null && parentNode.rightChild == null)
      Console.WriteLine(parentNode.data + "{" + code + "}");
    System.IO.File.AppendAllText("E:\\test.txt", code);
    GenerateCode(parentNode.rightChild, code + "1");
  }
}

and this is the decode function

public static void DecodeData(Node parentNode, Node currentNode, int pointer, string input)
{
  if (input.Length == pointer)
  {
    if (currentNode.leftChild == null && currentNode.rightChild == null)
    {
      Console.WriteLine(currentNode.data);
    }
    return;
  }
  else
  {
    if (currentNode.leftChild == null && currentNode.rightChild == null)
    {
      Console.WriteLine(currentNode.data);
      DecodeData(parentNode, parentNode, pointer, input);
    }
    else
    {
      if (input.Substring(pointer, 1) == "0")
      {
        DecodeData(parentNode, currentNode.leftChild, ++pointer, input);
      }
      else
      {
        DecodeData(parentNode, currentNode.rightChild, ++pointer, input);
      }
    }
  }
}

and this is my calling for the two function

GenerateCode(parentNode1, "");

string contents = File.ReadAllText(@"E:\\test.txt");
DecodeData(parentNode1, parentNode1, 0, contents); 
4
  • 1
    This GenerateCode method just saves existing tree into file; you're missing the Encode method; also general pointer - check out snipd.net/huffman-coding-in-c Aug 15, 2014 at 14:42
  • @OndrejSvejdar i know that my code just save the tree, i show the link you put in the comment i want to know how i improve my code i you can help me with a small code or demo to show that. and thanks for your help
    – conn
    Aug 15, 2014 at 15:03
  • 1
  • 1
    Can you show us an example of what you expect and what C# produces Aug 18, 2014 at 22:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.