High Five

/**
 * @param results a list of <student_id, score>
 * @return find the average of 5 highest scores for each person
 * Map<Integer, Double> (student_id, average_score)
 */
public Map<Integer, Double> highFive(Record[] results) {
    Map<Integer, Double> answer = new HashMap<>();
    Map<Integer, List<Integer>> hash = new HashMap<Integer, List<Integer>>();
    for(Record r : results){
        if(!hash.containsKey(r.id)){
            hash.put(r.id, new ArrayList<Integer>());
        }
        if(hash.get(r.id).size() < 5){
            hash.get(r.id).add(r.score);
        } else {
            int lowest_index = 0;
            for(int i = 1; i < 5; i++){
                if(hash.get(r.id).get(i) < hash.get(r.id).get(lowest_index)){
                    lowest_index = i;
                }
            }
            if(hash.get(r.id).get(lowest_index) < r.score){
                hash.get(r.id).set(lowest_index, r.score);
            }
        }
    }
    for(Map.Entry<Integer, List<Integer>> entry : hash.entrySet()){
        int id = entry.getKey();
        List<Integer> scores = entry.getValue();
        double average = 0.0;
        for(int i = 0; i < scores.size(); i++){
            average += scores.get(i);
        }
        average /= scores.size();
        answer.put(id, average);
    }
    return answer;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s