首页 > 解决方案 > 使用 C# 查找示例模式

问题描述

我有这样一个样本:[5,3,5,5,8,9,8,8,6,1]

我想找到模式。在这种情况下 5 和 8。

我已经实现了这样的方法:

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

但是输出是1,3

怎么了?

标签: c#statisticssamplemode

解决方案


您添加Dictionary 的counts它们是初始数组中相同数字的数量:

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

您可能想要添加keys以查看哪些数字有重复:

// int max = 0; <-- not needed

foreach (var key in counts.Keys)
{
    // Check that number from initial array (key)
    // have duplicates (value is more than 1)
    if (counts[key] > 1) 
    {
        // Add to result not amount of duplicates (value),
        // but number (key) which has duplicates
        result.Add(key);
    }
}

它将为您提供[5,3,5,5,8,9,8,8,6,1]数组中的58 。


推荐阅读