Search code examples
c#statisticssamplemode

Finding sample mode with C#


I have such a sample: [5,3,5,5,8,9,8,8,6,1]

And I'd like to find the mode(s). In this case 5 & 8.

I have implemented such a method:

static List<int> Mode(int[] array)
        {
            if (array.Length == 0)
            {
                throw new ArgumentException("Sample can't be empty");
            }
            List<int> result = new List<int>();
            var counts = new Dictionary<int, int>();
            int max = 0;
            foreach (int num in array)

            {
                if (counts.ContainsKey(num))
                    counts[num] = counts[num] + 1;
                else
                    counts[num] = 1;
            }

            foreach (var key in counts.Keys)
            {
                if (counts[key] > max)
                {
                    max = counts[key];
                    result.Add(max);
                }
            }

            return result;
        }

But the output is 1,3

What's wrong?


Solution

  • First you need to calculate the max in the first loop. Then in the second you can find the numbers that have a count equal to max and add the key, not the max to your result.

    static List<int> Mode(int[] array)
    {
        if (array.Length == 0)
        {
            throw new ArgumentException("Sample can't be empty");
        }
        List<int> result = new List<int>();
        var counts = new Dictionary<int, int>();
        int max = 0;
        foreach (int num in array)
        {
            if (counts.ContainsKey(num))
                counts[num] = counts[num] + 1;
            else
                counts[num] = 1;
            if(counts[num] > max)
                max = counts[num];
        }
    
        foreach (var key in counts.Keys)
        {
            if (counts[key] == max)
            {
                result.Add(key);
            }
        }
    
        return result;
    }