Search code examples
c#mode

C# Finding the Mode


In my program I'm trying to find the Mode from a list of integers. Logically wise my program is correct. However when I try to print out the Mode I get the following message "Mode: System.Collections.Generic.List'1[System.Int32]. The outcome I was expecting to print is "Mode: 2, 7" since these 2 numbers occur 3 times in the list of integers. What am I doing wrong here? Thanks in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mode
{
    class Program
    {
        static void Main(string[] args)
        {
            Test();
        }

        static void Test()
        {
            int[] values = { 1, 6, 4, 7, 9, 2, 5, 7, 2, 6, 5, 7, 8, 1, 3, 8, 2 };
            List<int> mode = new List<int>();

            mode = Mode(values);
            Console.WriteLine("Mode: {0}", mode);

            Console.ReadLine();
        }


        static List<int> Mode(int[] values)
        {
            int[] sorted = new int[values.Length];
            values.CopyTo(sorted, 0);
            Array.Sort(sorted);

            List<int> result = new List<int>();
            var counts = new Dictionary<int, int>();
            int max = 0;
            foreach (int num in sorted)

            {
                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;

        }
    }
}

Solution

  • user DesertFox mentioned properly. You are trying to print a list. Intead of that, as per your requirement, make it as a single string using String.Join.

    Modify your test method like below

        static void Test()
        {
            try
            {
                int[] values = { 1, 6, 4, 7, 9, 2, 5, 7, 2, 6, 5, 7, 8, 1, 3, 8, 2 };
                List<int> mode = new List<int>();
    
                mode = Mode(values);
                Console.WriteLine("Mode: {0}", String.Join(", ", mode));
                Console.ReadLine();
            }
            catch(Exception ex)
            {
    
            }
        }
    

    Output

    enter image description here