如何在我的问题中创建频率计数器? [英] how to create frequency counter in my problem?

查看:78
本文介绍了如何在我的问题中创建频率计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


大家好!!!帮助解决我的问题.
我正在使用C#,数组中有以下数据.


Hello every body!!! help with my problem.
i''m using c# i have the following data in my array.

a[0]=2
a[1]=2
a[2]=4
a[3]=5
a[4]=5
a[5]=5
a[6]=6
a[7]=6
.
.
.


然后我想从数组中收集信息为:


then i want to collect information from the array as:

2 has frequency of 2
4 has frequency of 1 has frequency of 3
6 has frequency of 2


那么我该如何将该信息存储在两个维数组或其他包含值(2,4,5 ...)及其频率(2,1,3,...)的数组中,其中的大小和值给定的数组是动态的.

[edit]从C#问题中删除了C ++标签. OriginalGriff [/edit]


then how can i store this information in two diamentional array or other if any that hold the value (2,4,5...) and its frequency (2,1,3,...) .where the size and value of the given array is dynamic.

[edit]Removed C++ tags from C# question. OriginalGriff[/edit]

推荐答案

使用字典< int,int>这可以使其成长:

Use a Dictionary<int, int> This allows it to grow:

Dictionary<int, int> counts = new Dictionary<int,int>();
foreach (int i in a)
    {
    if (counts.ContainsKey(i))
        {
        counts[i]++;
        }
    else
        {
        counts.Add(i, 1);
        }
    }
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<int, int> kvp in counts)
    {
    sb.Append(string.Format("{0} has {1}\n", kvp.Key, kvp.Value));
    }
MessageBox.Show(sb.ToString());


如果知道元素总数,则不需要多维数组.

您可以创建另一个临时数组来存储计数,在上运行循环并为每个数字增加数组元素

If you know the total number of elements you have, you dont need a multidimensional array for this.

You could just create another temp array that stores the count, run a loop on a and increment the array element for each number

for(int i;i<=TotalNumberCounter;i++)<br />
{<br />
   temp[a[i]]++;<br />
}



循环完成后,临时数组将包含每个元素的计数.

[edit]不是您需要的总数,而是最大的数目!而且要知道它们都不是负面的...:laugh:OriginalGriff [/edit]



Once the loop completes, the temp array will contain the count for each of your elements.

[edit]It''s not the total number of counts you need, it''s the largest! And to know that none of them are negative, of course... :laugh: OriginalGriff[/edit]


这篇关于如何在我的问题中创建频率计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆