Mrs. Jhunjhunwala has taught Programming in Java to the second-year students in ICE college and conducted 3 academic tasks for all the (N) students. Marks are store in a 2-D array but now Mrs. Jhunjhunwala is willing to implement a java program which can accept the 2-D array of marks and return the average marks of Best 2 Academic Tasks of each student. Help her to implement a method public double[] average_marks(double [][] marks)
Input Format
First line reads the number of students N
Next N lines read the marks of each student seperated by space
Constraints
n>0
Output Format
Prints the Avaerage marks of best 2 Academic tasks of N students separated by space
Sample Input 0
2
10.5 2.5 15
5.25 6.75 11.25
Sample Output 0
12.75 9.0
Solution
step-by-step:
- The
average_marks
method takes a 2D arraymarks
as input, wheremarks[i][j]
represents the mark obtained by thei
-th student in thej
-th academic task. - It initializes an array
averages
to store the average marks of each student. - For each student, it creates a new
Double
arraysortedMarks
that contains the marks of that student, and sorts it in descending order usingArrays.sort(sortedMarks, Collections.reverseOrder())
. Note that we can’t directly sort a primitivedouble
array usingCollections.reverseOrder()
, so we need to convert thedouble
array to aDouble
array first. - It then calculates the sum of the best 2 marks of each student using the
sortedMarks
array, and divides it by 2 to get the average of the best 2 marks. - The method stores the average in the
averages
array. - Once the loop has finished iterating over all the students, the
average_marks
method returns theaverages
array.
import java.io.*;
import java.util.*;
public class Main {
public static double[] average_marks(double[][] marks) {
int n = marks.length;
double[] averages = new double[n];
for (int i = 0; i < n; i++) {
double sum = 0;
Double[] sortedMarks = new Double[3];
for (int j = 0; j < 3; j++) {
sortedMarks[j] = marks[i][j];
}
// sauravhathi
Arrays.sort(sortedMarks, Collections.reverseOrder());
for (int j = 0; j < 2; j++) {
sum += sortedMarks[j];
}
averages[i] = sum / 2;
}
return averages;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[][] marks = new double[n][3];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
marks[i][j] = sc.nextDouble();
}
}
double[] averages = average_marks(marks);
for (int i = 0; i < n; i++) {
System.out.print(averages[i] + " ");
}
}
}
Happy Learning – If you require any further information, feel free to contact me.