How to count the frequency of bundle of number using c#?

前端 未结 5 1153
遇见更好的自我
遇见更好的自我 2020-12-12 06:21

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 07:10

    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 Counts = new Dictionary();
    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 kvp in Counts)
    {
        Console.Write("{0} - {1}",kvp.Key,kvp.Value);
    }
    

提交回复
热议问题