首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用c#统计数字捆绑的频率?

如何使用c#统计数字捆绑的频率?
EN

Stack Overflow用户
提问于 2012-03-11 16:38:36
回答 5查看 2.9K关注 0票数 0

有人能帮我用c#运行这个程序吗?本程序是计算出现频率的数字,例如12出现10倍。在此之前,我尝试在水平线中对所有列表编号进行排序。然后我比较相同的数字,然后是count++,但直到知道,我才能得到输出。

谢谢你的帮助。

输入

46 31 46 9 25 12 45 33 25 12 12 12 28 36 38 28 25 12 9 36 36 36 12 9 36 12 25 28 34 36 36 9 12 16 25 28 44

输出

9-4 12 -10 16 -1 25 -5 28 -4 31 -1 33 -1 34 -1 36 -7 38 -2 44 -1 45 -1 46 -2

EN

回答 5

Stack Overflow用户

发布于 2012-03-11 16:44:22

嗯,您可以使用Dictionary<int, int>手动完成此操作

代码语言:javascript
复制
var frequencies = new Dictionary<int, int>();
foreach (var item in data)
{
    int currentCount;
    // We don't care about the return value here, as if it's false that'll
    // leave currentCount as 0, which is what we want
    frequencies.TryGetValue(item, out currentCount);
    frequencies[item] = currentCount + 1;
}

一种更简单但效率较低的方法是使用LINQ:

代码语言:javascript
复制
var frequencies = data.ToLookup(x => x) // Or use GroupBy. Equivalent here...
                      .Select(x => new { Value = x.Key, Count = x.Count() })
                      .ToList();
foreach (var frequency in frequencies)
{
    Console.WriteLine("{0} - {1}", frequency.Value, frequency.Count);
}
票数 4
EN

Stack Overflow用户

发布于 2012-03-11 16:45:55

假设你有一个数字列表:

代码语言:javascript
复制
var numbers = new List<int>{ 1, 2, 3, 4, 1, 2, 2, 3 };

然后我们可以使用Linq来实现您想要的功能:

代码语言:javascript
复制
var frequencies = 
    numbers.GroupBy( n => n ).Select( n => new { Value=n.Key, Count=n.Count() } );

foreach (var f in frequencies)
{
    Debug.WriteLine(string.Format("Value={0}, Frequency={1}", f.Value, f.Count));
}
票数 2
EN

Stack Overflow用户

发布于 2012-03-11 16:44:10

我会使用int和int: dictionary的字典,并在遍历数字的同时加1。一些解决方案使用数组,但我更喜欢字典,因为它消除了管理数组大小的需要,并且内存效率更高。

代码语言:javascript
复制
int[] someValues = { /* your numbers */ }
Dictionary<int,int> Counts = new Dictionary<int,int>();
foreach(int key in someValues)
{
    if ( !Counts.HasKey(key) ) Counts[ key ] = 0;
    Counts[key] = Counts[key] + 1;
}

然后,您只需迭代字典以获得输出:

代码语言:javascript
复制
foreach(KeyValuePair<int,int> kvp in Counts)
{
    Console.Write("{0} - {1}",kvp.Key,kvp.Value);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9653566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档