using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
//Step 1: Get string from user
//Step 2: Find out how many times each character in the string repeats
//Step 3: find the two characters that repeat the least adding their frequency and add them together with the sum of their frequencies
//step 4: Add this new sum back into the list, wherever it will now go, higher up
//step 5: repeat theses steps, until you have a huffman tree!
namespace HuffmanTree
{
class Program
{
static void Main(string[] args)
{
HuffmanTree.GetValue();
}
}
class HuffmanTree
{
public static void GetValue()
{
Console.WriteLine("Write a string to be encoded"); //Here we are asking the user to input a string
string encodeme = Console.ReadLine(); // here the user inputs their string, which gets declared as the variable "encodeme"
Dictionary<char, int> timesRepeated = new Dictionary<char, int>();
List<Node> HuffmanNodes = new List<Node>();
foreach (char ch in encodeme.Replace(" ", string.Empty))
{
if (timesRepeated.ContainsKey(ch))
{
timesRepeated[ch] = timesRepeated[ch] + 1;
}
else
{
timesRepeated.Add(ch, 1);
}
}
foreach (KeyValuePair<char, int> item in timesRepeated.OrderByDescending(i => i.Value))
{
char key = item.Key;
int count = item.Value;
Console.WriteLine(key.ToString() + " : " + count.ToString());
HuffmanNodes.Add(new Node());
}
Console.WriteLine(HuffmanNodes(node));
}
public class Node //These are going to be the intialisation of our nodes
{
public char Symbol { get; set; }
public int Frequency { get; set; }
public Node Right { get; set; }
public Node Left { get; set; }
}
}
}
我正在尝试console.write我的霍夫曼树节点列表,以便我可以看到发生了什么。打印控制台.WriteLine(HuffmanNodes(node));似乎不起作用。我尝试打印几种不同的方法,例如[i],但似乎不起作用。这是用于调试,因此我可以看到每个步骤的操作。
您正在尝试像方法一样调用HuffmanNodes
,因为它是List<>
,因此需要枚举它...
foreach (Node node in HuffmanNodes)
{
Console.WriteLine($"Symbol: {node.Symbol}, Frequency: {node.Frequency}");
}
...或对其进行迭代...
for (int i = 0; i < HuffmanNodes.Count; i++)
{
Console.WriteLine($"Symbol: {HuffmanNodes[i].Symbol}, Frequency: {HuffmanNodes[i].Frequency}");
}
...访问它包含的每个Node
。
您也可以只包含代码以在前面的foreach
循环中显示列表,因为那样您就可以按添加到Node
的顺序访问相同的List<>
。 。
foreach (KeyValuePair<char, int> item in timesRepeated.OrderByDescending(i => i.Value))
{
// [snip]
Node node = new Node();
HuffmanNodes.Add(node);
Console.WriteLine($"Symbol: {node.Symbol}, Frequency: {node.Frequency}");
}
附加说明:
Node
的HuffmanNodes
的任何属性。override
类的ToString()
method,则可以与上面的我的ToString()
调用相同的方式构建诊断Node
。这将允许您使用string
打印Console.WriteLine()
的属性。Node
的方法很奇怪。