有人能帮我用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
发布于 2012-03-11 16:44:22
嗯,您可以使用Dictionary<int, int>手动完成此操作
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:
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);
}发布于 2012-03-11 16:45:55
假设你有一个数字列表:
var numbers = new List<int>{ 1, 2, 3, 4, 1, 2, 2, 3 };然后我们可以使用Linq来实现您想要的功能:
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));
}发布于 2012-03-11 16:44:10
我会使用int和int: dictionary的字典,并在遍历数字的同时加1。一些解决方案使用数组,但我更喜欢字典,因为它消除了管理数组大小的需要,并且内存效率更高。
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;
}然后,您只需迭代字典以获得输出:
foreach(KeyValuePair<int,int> kvp in Counts)
{
Console.Write("{0} - {1}",kvp.Key,kvp.Value);
}https://stackoverflow.com/questions/9653566
复制相似问题