Skip to content

Instantly share code, notes, and snippets.

@rosenpin
Created January 19, 2016 18:02
Show Gist options
  • Save rosenpin/5685b58e5471bfba3efb to your computer and use it in GitHub Desktop.
Save rosenpin/5685b58e5471bfba3efb to your computer and use it in GitHub Desktop.
static void printBestSubject(Node<Students> students) {
//Defining number of subjects to minimum
int numberOfSubjects = 0;
//Defining number of students to minimum
int numberOfStudents = 0;
//Defining a temp students node
Node<Students> student = students;
//Defining a temp grade node
Node<Grade> tempGrade = student.getData().getGrade();
//Checking the number of subjects for every student
while (tempGrade != null) {
tempGrade = tempGrade.getLink();
numberOfSubjects++;
}
//Defining 2 arrays, one for the grade of every subject
int[] gradesForSubjects = new int[numberOfSubjects];
//And one for ID of every subject
int[] subjectsIDs = new int[numberOfSubjects];
//Resetting the temp student node
student = students;
//Resetting the temp grade node
tempGrade = student.getData().getGrade();
//Filling in the arrays we created earlier with the correct information
while (student != null) {
for (int i = 0; i < numberOfSubjects; i++) {
gradesForSubjects[i] += tempGrade.getData().getScore(); //Adding score for every students grade
subjectsIDs[i] = tempGrade.getData().getID();//Setting the subject ID
tempGrade = tempGrade.getLink();//Next grade
}
student = student.getLink();//Next student
tempGrade = student.getData().getGrade();//Setting the base grade of the next student
numberOfStudents++;//Update the students counter for later
}
int bestScore = 0, bestScoreID = 0; //Setting counters
for (int i = 0; i < gradesForSubjects.length; i++) {//Checking every score
if (bestScore < (gradesForSubjects[i] / numberOfStudents)) //If the subject average is the highest
{
bestScore = gradesForSubjects[i] / numberOfStudents; //Update the counter
bestScoreID = subjectsIDs[i]; //Update the ID
}
}
System.out.println(String.valueOf(bestScoreID)); //Print the highest averaged subject
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment