亚麻:high 5 score

 

input是一个arraylist,里面每一个element是一个pair,studentid和他的一个score。code就是要把这个list里面的所有学生的所有分数都读进去 然后计算每一个学生最高5个分数的平均值 然后output一个map key是id value是平均分.

#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector
#include <unordered_map>
#include <numeric>
#include <list>
#include <numeric>

//key point
//use map< studentid , vector< scores>> to store the scores
//that method is similar with the distribute storage system. the code is very simple and clear.

//then sor scores of each stduent. and sum the first five scores.

using namespace std;


unordered_map <int ,int> highFiveScores( list< pair<int,int>>& scores){
    //if the need to check the # of each student score is not less than five?
    unordered_map<int , vector<int>> studentscores;
    unordered_map<int , int> res;
    
    for (auto& e: scores)
        studentscores[e.first].push_back(e.second);
    
    for (auto& e: studentscores){
        vector<int>& temp = e.second;
        
        sort(temp.begin(), temp.end(), [](int x, int y ){ return x >y;} );
        int sum = accumulate (temp.begin(), temp.begin() + 5,0);
        res[e.first] = sum/5 ;
    }
    return res;
}

int main () {
    
    list<pair <int,int>> in = {{1,10},{1,30},{1,30},{1,40},{1,50},{1,60},{2,30},{2,40},{2,50},{2,60},{2,70},{2,80},{1,90},{1,90},{1,80},{2,10}};
    unordered_map<int ,int > out ;
    out = highFiveScores(in);
    for (auto& e: out )
        cout<< e.second << endl;
    return 0;
}

 

posted @ 2018-01-17 13:33  HisonSanDiego  阅读(141)  评论(0编辑  收藏  举报