【问题标题】:Sort dictionary values into descending order [duplicate]将字典值按降序排序[重复]
【发布时间】:2020-08-26 11:57:38
【问题描述】:

我的任务:

  1. 从用户那里获取字符串
  2. 找出字符串中每个字符重复的次数
  3. 找出重复次数最少的两个字符,将它们的频率相加,然后将它们加上它们的频率之和
  4. 将这个新的总和重新添加到列表中,无论它现在去哪里,更高
  5. 重复这些步骤,直到得到一棵霍夫曼树!

我的代码:

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>();

        foreach (char ch in encodeme.Replace(" ", string.Empty))
        {
            if (timesRepeated.ContainsKey(ch))
            {
                timesRepeated[ch] = timesRepeated[ch] + 1;
            }
            else
            {
                timesRepeated.Add(ch, 1);
            }
        }

        foreach (var item in timesRepeated.Keys)
        {
            Console.WriteLine(item + " : " + timesRepeated[item]);
        }

        Console.ReadKey();
    }
}

class Node
{

}

所以我试图将字典值“重复次数”按降序排序,这样当它打印出字符重复的次数时,它会按降序显示这些值。

例如,如果我输入了字符串“BOOOM”

O = 3
B = 1
M = 1

此刻它说:

B = 1
O = 3
M = 1

我不知道该怎么做!!!

【问题讨论】:

  • this 回答你的问题了吗?

标签: c#


【解决方案1】:

目前您正在枚举键集合,但实际上您可以枚举字典本身,这意味着您获得了一个键/值对象:

foreach(KeyValuePair<char, int> item in timesRepeated)
{
    char key = item.Key;
    int count = item.Value;
    Console.WriteLine(key.ToString() + " : " + count.ToString());
}

这对我们有什么帮助?好吧,我们可以将它与.OrderByDescending LINQ 方法结合使用:

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());
}

您可能还想按字母顺序排序,然后您可以使用ThenBy

foreach(KeyValuePair<char, int> item in timesRepeated.OrderByDescending(i => i.Value).ThenBy(i => i.Key))
{
    char key = item.Key;
    int count = item.Value;
    Console.WriteLine(key.ToString() + " : " + count.ToString());
}

注意:这只会对罗马字母(A、B 等)进行字母顺序。

注意 2:如果文件不存在,您可能需要在文件顶部添加 using System.Linq;

Try it online

结果:

O : 3
B : 1
M : 1

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多