问题
Can somebody help me to run this program using c#. This program is to calculate the frequency of the number, for example 12 appear 10x. Before this I try to sort all list number in a horizontal line. Then I compare the same number, then count++, but until know I can’t get the output.
Thanks for helping.
INPUT
46 31 46 9 25 12 45 33 25 12 12 12 28 36 38 28 25 12 12 9 36 38 36 36 12 9 36 12 12 25 28 34 36 36 9 12 16 25 28 44
OUTPUT
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
回答1:
Well, you could do this manually using a 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;
}
A simpler but less efficient approach would be to use 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);
}
回答2:
Assuming you have a list of numbers:
var numbers = new List<int>{ 1, 2, 3, 4, 1, 2, 2, 3 };
Then we can use Linq to achieve what you want:
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));
}
回答3:
I would put them all into a list then use a group by clause to group them ie
List<int> numbers = new List<int> { 1, 2, 2, 3, 5, 6, 2, 1, 4, 4 };
foreach (var group in numbers.GroupBy(n => n))
{
Console.WriteLine("{0} was found {1} times", group.Key, group.Count());
}
回答4:
I would use a dictionary of int and int: Dictionary and iterate through the numbers adding 1 as you go. some solutions use an array, but I prefer a dictionary this eliminates the need to manage the size of the array and is more memory efficient.
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;
}
then, you just iterate over the dictionary for your output:
foreach(KeyValuePair<int,int> kvp in Counts)
{
Console.Write("{0} - {1}",kvp.Key,kvp.Value);
}
回答5:
Homework assignment? We're not here to do homework assignments for you, but I will give you advice on what to do.
First, I would have a text reader so your input can be inputted. Then, parse each entry and add it into a dictionary. Then, iterate thru the dictionary to see how many times a specific entry occurs.
来源:https://stackoverflow.com/questions/9653566/how-to-count-the-frequency-of-bundle-of-number-using-c