【问题标题】:Finding sample mode with C#使用 C# 查找示例模式
【发布时间】:2021-12-08 01:54:30
【问题描述】:

我有这样一个样本:[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

怎么了?

【问题讨论】:

  • 模式是什么意思?
  • 一个问题是您将计数而不是数字添加到列表中。但即使你修复了这个问题,你最终也会从字典中添加第一个键,因为它的计数高于 1。你需要先确定最大值,然后找到计数等于该值的所有数字。
  • @Hazrelle Mode 是数据集中出现频率最高的一个或多个数字。

标签: c# statistics sample mode


【解决方案1】:

首先您需要在第一个循环中计算max。然后在第二个中,您可以找到计数等于 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;
}

【讨论】:

  • 最合适的方案,非常感谢
【解决方案2】:

您添加了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);
    }
}

它会给你 58 来自 [5,3,5,5,8,9,8,8,6,1] 数组。

【讨论】:

  • 虽然这适用于 [1,1,2,2,2] 这样的集合的示例数据集,但模式是 [2],而不是 [1,2]。基本上它是假设找到在数据集中出现最多的一个或多个数字,而不是所有出现多次的数字。
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 1970-01-01
  • 2016-06-30
相关资源
最近更新 更多