Created
August 20, 2024 22:33
-
-
Save ValchanOficial/3ebbf01b3de40ec326d3994c5286446b to your computer and use it in GitHub Desktop.
[The Daily Byte][Student Averages]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Question from: https://thedailybyte.dev/ | |
// You are given a two-dimensional matrix that represents the grades of a class of students. Each grade is represented as an array where the first index is the student’s ID and the second student is a grade (0 - 100) that the student has received. Given these grades, calculate the average of each student’s top five scores and return the result. | |
// Note: Each student is guaranteed to have at least 5 scores. Student IDs start from zero and increase by one. Your return variable should be sorted according to student ID. | |
My solution: | |
const grades = [[1, 100], [1, 50], [2, 100], [2, 93], [1, 39], [2, 87], [1, 89], [1, 87], [1, 90], [2, 100], [2, 76]] | |
const averageGrade = (grades) => { | |
let studentGrades = {} | |
let result = [] | |
for (let i = 0; i < grades.length; i++) { | |
const [studentId, grade] = grades[i] | |
if (studentGrades[studentId]) { | |
studentGrades[studentId].push(grade) | |
} else { | |
studentGrades[studentId] = [grade] | |
} | |
} | |
for (let key in studentGrades) { | |
studentGrades[key].sort((a, b) => b - a) | |
let sum = 0 | |
for (let i = 0; i < 5; i++) { | |
sum += studentGrades[key][i] | |
} | |
result.push([parseInt(key), Math.floor(sum / 5)]) | |
} | |
return result | |
} | |
console.log(averageGrade(grades)) // [[1, 83], [2, 91]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment