Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

java - Calculating the average?

I am having problem with this question:

Given a list of test results (each with a test date, Student ID, and the student’s Score); return the Final Score for each student. A student’s Final Score is calculated as the average of his/her 5 highest test scores. You can assume each student has at least 5 test scores.

Now, here is the thing. I do not want the answer.

I tried the hashing, but hashing can provide key with addresses so it did not work for me.

I thought of using array list the iterate thought to calculate the average and return the top five score, but how do I assign the numbers with the studentID ?

Say I want the output to be: Mike, 15. Is not this what the question requires ? To get the student ID and the average number. Please, help me out with some clues, I am learning.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just sort the test results by student ID (as the major sort key) and descending score (minor sort key) then go through the collection as follows (pseudo-code):

lastId = element[0].Id - 1
for each record in element[]:
    if record.Id != lastId:
        lastId = record.Id
        counter = 5
        sum = 0
    if counter > 0:
        sum = sum + record.score
        counter = counter - 1
        if counter == 0:
            print "Student ", record.Id, " got average of ", (sum / 5)

Because the data is sorted, you know that all the scores for a given student are together and that the first five of them are the highest. Hence the above code will allow you to work it all out.

Keep in mind this relies on your "every student has at least five results" rule. Without that, you'd have to change the average calculation code and possibly do some post-work loop on the last student.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...