使用 C# 查找示例模式

Finding sample mode with 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

怎么了?

您添加 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 & 8 from [5,3,5,5,8,9 ,8,8,6,1] 数组。

首先你需要计算第一个循环中的max。然后在第二个中,您可以找到计数等于最大值的数字,并将 key 而不是 max 添加到结果中。

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