Algorithm to compute mode

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

    If you simply wish to count the number of occurences then I suggest you use a std::map or std::unordered_map.

    If you're mapping a counter to each distinct value then it's an easy task to count occurences using std::map as each key can only be inserted once. To list the distinct numbers in your list simply iterate over the map.

    Here's an example of how you could do it:

    #include 
    #include 
    #include 
    #include 
    
    std::map getOccurences(const int arr[], const std::size_t len) {
        std::map m;
        for (std::size_t i = 0; i != len; ++i) {
            m[arr[i]]++;
        }
        return m;
    }
    
    int main() {
        int list[7]{1, 1, 1, 1, 2, 2, 2};
        auto occurences = getOccurences(list, 7);
        for (auto e : occurences) {
            std::cout << "Number " << e.first << " occurs ";
            std::cout << e.second << " times" << std::endl;
        }
        auto average = std::accumulate(std::begin(list), std::end(list), 0.0) / 7;
        std::cout << "Average is " << average << std::endl;
    }
    

    Output:

    Number 1 occurs 4 times
    Number 2 occurs 3 times
    Average is 1.42857
    

提交回复
热议问题