C#计算众数

    public class CalculateModeTool<T> where T : struct
    {
        // 源数据
        private List<T> source;

        // 构造函数
        public CalculateModeTool(List<T> source)
        {
            this.source = source;
        }

        // 计算众数
        public Dictionary<T, int> Calculate()
        {
            Dictionary<T, int> dictionary = new Dictionary<T, int>();
            foreach (T item in source)
            {
                if (!dictionary.ContainsKey(item))
                {
                    dictionary.Add(item, 1);
                }
                else
                {
                    dictionary[item]++;
                }
            }

            // 众数不存在
            int first = dictionary.OrderBy(m => m.Value).First().Value;
            int last = dictionary.OrderBy(m => m.Value).Last().Value;
            if (last == 1)
            {
                return null;
            }
            if (last == first)
            {
                return null;
            }

            // 获取众数
            Dictionary<T, int> result = new Dictionary<T, int>();
            foreach (KeyValuePair<T, int> kvp in dictionary)
            {
                if (kvp.Value == last)
                {
                    result.Add(kvp.Key, kvp.Value);
                }
            }
            return result;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<int> source = new List<int>() { 1, 1, 2, 2, 0, 1, 3, 3 };
            CalculateModeTool<int> tool = new CalculateModeTool<int>(source);
            Dictionary<int, int> dictionary = tool.Calculate();
            if (dictionary == null)
            {
                Console.WriteLine("众数不存在");
            }
            else
            {
                foreach (KeyValuePair<int, int> kvp in dictionary)
                {
                    Console.WriteLine(kvp.Key);
                }
            }
            Console.ReadKey(true);
        }
    }

猜你喜欢

转载自blog.csdn.net/HerryDong/article/details/84112935
今日推荐