Algorithm to compute mode

前端 未结 4 1852
孤独总比滥情好
孤独总比滥情好 2021-01-12 04:42

I\'m trying to devise an algorithm in the form of a function that accepts two parameters, an array and the size of the array. I want it to return the mode of the array and i

4条回答
  •  被撕碎了的回忆
    2021-01-12 05:25

    Even though you have some good answers already, I decided to post another. I'm not sure it really adds a lot that's new, but I'm not at all sure it doesn't either. If nothing else, I'm pretty sure it uses more standard headers than any of the other answers. :-)

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        std::vector inputs{ 1, 1, 1, 1, 2, 2, 2 };
    
        std::unordered_map counts;
        for (int i : inputs)
            ++counts[i];
    
        std::multimap > inv;
        for (auto p : counts)
            inv.insert(std::make_pair(p.second, p.first));
    
        auto e = inv.upper_bound(inv.begin()->first);
    
        double sum = std::accumulate(inv.begin(),
            e,
            0.0,
            [](double a, std::pair const &b) {return a + b.second; });
    
        std::cout << sum / std::distance(inv.begin(), e);
    }
    

    Compared to @Dietmar's answer, this should be faster if you have a lot of repetition in the numbers, but his will probably be faster if the numbers are mostly unique.

提交回复
热议问题