0
\$\begingroup\$

My homework asks me to define a 2d array and find the max value, and the min value in the index of the max value here's how I did it

public class Main {
public static void main(String[] args) {
int[][] ar = {{11,12,9,14,60},{200,50,23,19,25},{31,100,33,34,35}};
int max = ar[0][0];
int y = 0;
for (int i = 0; i <ar.length;i++){
    for (int k=0;k < ar[i].length;k++){
        if (ar[i][k] > max) {
            max = ar[i][k];
            y = i;
        }
    }
}
int minInMaxLine = ar[y][0];
for (int i =0;i<ar[y].length;i++){
    if (ar[y][i] < minInMaxLine){
        minInMaxLine = ar[y][i];
    }
}
System.out.println("Max value is : "+max);
System.out.println("Index of max value is : "+y);
System.out.println("Min value in max value's index is : "+minInMaxLine);

 }
}

this outputs :

Max value is : 200

Index of max value is : 1

Min value in max value's index is : 19

\$\endgroup\$
1
\$\begingroup\$

This approach looked great I think you should try to consider more cases then the ones you added in your example your algorithm should consider cases as if the 2d array was null as well. For reference please click here.

\$\endgroup\$
0
\$\begingroup\$

I don't think it can get much simpler or more straightforward than your code. One way to improve upon what you already have is to also handle the case that the maximum value occurs more than once. True, the exercise does not prescribe how to deal with this situation, but it's something you might want to consider.

You could also choose a more meaningful variable name for y, like you did with the other variables.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.