【问题标题】:Using double arrays to find the mode?使用双数组查找模式?
【发布时间】:2017-07-12 19:55:42
【问题描述】:

我被困在如何编写一个函数,该函数使用该数组及其长度作为参数来查找数组中包含的一组整数的模式或模式。我在网上找到了多个关于如何找到数组模式的解决方案,但我正在尝试通过以下方式解决这个问题:

假设原始数组包含 (0, 0, 1, 5, 5, 5, 7, 7, 7)。我想用一个循环遍历数组,找到任意数量的最高频率而不存储模式,并将这些频率存储在另一个数组中,在这种情况下,新数组将具有值 (1, 2, 1, 1、2、3、1、2、3)。通过在第二个数组中找到最大值,我会找到最高频率,在这种情况下为 3。然后我想再次遍历原始数组,将最高频率与该数组中每个值的计数进行比较,在匹配的地方,我返回那个值,在这个例子中我是 5 和 7给予。鉴于此处的标准,您将如何编写此函数来查找给定数组的模式或模式? (您可以假设数组已经按升序进行了预排序)。

编辑:这是我的初步代码。我已经完成了找到原始数组中每个整数的频率并将它们存储到另一个数组中的步骤。

    void findMode(int array, int size){ 
        int count = 1;
        int freq[size];
        freq[0] = count;
        for (int pass = 1; pass < size; pass++){
            if (array[pass] == array[pass-1]){
            count++;
            freq[pass] = count;
            } 
          else{
              count = 1;
              freq[pass] = count;
              }
      }   

【问题讨论】:

  • std::sort(array.begin(),array.end()); 他们先,然后迭代。
  • 如何使用以键为整数、以值为出现次数的映射。每次再次看到相同的键时,增加值。尽管我不确定除非您遍历整个内容,否则您将如何确定最大值。编辑:这个问题在这里显示了同样的事情stackoverflow.com/a/9370990/1083027 只是保持最大的运行计数
  • 等等,你为什么要这个?为什么不保留一个等于列表中最大数字的值的列表,如果找到一个高于最大值的值,则将其擦除?

标签: c++ arrays mode


【解决方案1】:

如果您不介意一些额外的存储空间(可能是 O(N) 存储空间),您可以使用 std::map 来获取计数,然后线性搜索最常见的数字。

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <map>
#include <vector>

template<class InputIterator>
auto mode(InputIterator first, InputIterator last)
{
    using key_type = typename std::iterator_traits<InputIterator>::value_type;
    std::map<key_type, std::size_t> counts;
    for (auto it = first; it != last; ++it) {
        counts[*it]++;    
    }    
    return *std::max_element(counts.cbegin(), counts.cend(), [](auto const& lhs, auto const& rhs) {
        return lhs.second < rhs.second;
    }); // return mode + frequency
}

int main() {   
    auto v = std::vector<int> { 0, 0, 1, 5, 5, 5, 7, 7, 7 };   
    auto m = mode(v.cbegin(), v.cend());
    std::cout << m.first << ": " << m.second;
}

Live Example // 打印 5:3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2021-04-28
    • 1970-01-01
    • 2012-07-10
    • 2017-07-18
    • 2011-09-27
    相关资源
    最近更新 更多