Algorithm to compute mode

前端 未结 4 1855
孤独总比滥情好
孤独总比滥情好 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:10

    Based on the comment, it seems you need to find the values which occur most often and if there are multiple values occurring the same amount of times, you need to produce the average of these. It seems, this can easily be done by std::sort() following by a traversal finding where values change and keeping a few running counts:

    template 
    double mode(int const (&x)[Size]) {
        std::vector tmp(x, x + Size);
        std::sort(tmp.begin(), tmp.end());
        int    size(0);  // size of the largest set so far
        int    count(0); // number of largest sets
        double sum(0);    // sum of largest sets
        for (auto it(tmp.begin()); it != tmp.end(); ) {
            auto end(std::upper_bound(it, tmp.end(), *it));
            if (size == std::distance(it, end)) {
                sum += *it;
                ++count;
            }
            else if (size < std::distance(it, end)) {
                size = std::distance(it, end);
                sum = *it;
                count = 1;
            }
            it = end;
        }
        return sum / count;
    }
    

提交回复
热议问题