霍夫曼树不工作的算法

时间:2014-11-21 09:33:47

标签: c# huffman-code

我正在尝试创建一个Huffman Tree拉链。我开始使用类Node作为类型创建List,并且输入字符串中的字符应该添加到列表中?但是为什么我不能打印列表(字符串中char的char和频率)?

private void btnKomprimer_Click(object sender, System.Windows.RoutedEventArgs e)
{
    int k = 0;
    string input;
    char karakter;
    input = txtInput.Text;
    input = input.ToLower();
    txtOutput.Text = "";

    List<Node> noder = new List<Node>();
    for (int i = 0; i < input.Length; i++)
    {   
        karakter = input[i];

        for (int j = 0; j < noder.Count; j++)
        {
            if (noder[j].ErTegn(karakter) == true)
            {
                noder.Add(new Node(karakter));
            }
            else
            {
                noder[j].ØkMed1();
            }
        }
    }
    while (noder[k] != null)
    {
        txtOutput.Text += noder[k].Resultat();
        k++;
    }
}

public class Node
{
    public int frekvens;
    public char tegn;

    public Node (char c)
    {
        frekvens = 1;
        tegn = c;
    }

    public void ØkMed1()
    {
        frekvens = frekvens + 1;
    }

    public bool ErTegn(char c)
    {
        if ( c == tegn)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public string Resultat()
    {
        string resultat;
        resultat = Convert.ToString(tegn) + Convert.ToString(frekvens) + "\n";
        return resultat;
    }
}

2 个答案:

答案 0 :(得分:0)

搞砸了你的算法。当字符不在列表中时,必须添加到noder列表。项目数(noder.Count)将始终为0,因为您只在该循环中添加Node,该循环从0迭代到noder.Count:

for (int j = 0; j < noder.Count; j++) // noder.Count is always 0

请改为尝试:

List<Node> noder = new List<Node>();
for (int i = 0; i < input.Length;i++)
{   
    karakter = input[i];

    bool found = false;
    for (int j = 0; j < noder.Count;j++)
    {
        if (noder[j].ErTegn(karakter) == false)
        {
            noder[j].ØkMed1();
            found = true;
            break;
        }
    }
    if(!found)
    {
        noder.Add(new Node(karakter));
    }
}
foreach(Node n in noder)
{
    txtOutput.Text += n.Resultat();
}

答案 1 :(得分:0)

我建议使用Dictionary而不是列表。您可以将字符与输入文本中出现的次数进行存储。例如:

Dictionary<char, int> occurrences = new Dictionary<char, int>();

foreach (char c in input)
{
    if (occurrences.ContainsKey(c))
    {
        occurrences[c]++;
    }
    else
    {
        occurrences[c] = 1;
    }
}

字典由键/值对组成(其类型在尖括号中设置)。您可以通过执行以下操作来迭代它们:

txtOutput.Text = "";
foreach (KeyValuePair<char, int> pair in occurrences)
{
    txtOutput.Text += pair.Key + " : " + pair.Value + 
        Environment.NewLine;
}

然而,这将为您提供无序列表。要订购它,您可以查看LINQ的OrderBy功能,这非常酷:

http://msdn.microsoft.com/en-us/library/vstudio/bb534966%28v=vs.100%29.aspx

这意味着您可以将foreach行编写为:

foreach (KeyValuePair<char, int> pair in occurrences.OrderBy(pair => pair.Key))

按字符键对字典进行排序。

我希望这对你的学习有所帮助,祝你好运:)