tags:

views:

135

answers:

1

I have an array called Names[5] and one called scores[5][5]. Each row corresponds with the name in the respective index.

I need to find the highest score in the scores array and return the name that corresponds with it.

This is what I have so far:

int high = 0;
for(a=0; a<5; a++)
    for(b=0; b<5; b++)
        if(high<scores[a][b])
+4  A: 

Just scan the matrix, and remember the best score and best name so far. Something like:

String[] names = {"a","b","c","d","e"};
int[][] scores = new int[5][5];
//... init scores

int best = Integer.MIN_VALUE;
String bestName = null;
for(int nm = 0;nm<5;nm++){
    for(int c = 0;c<5;c++){
        int score = scores[nm][c];
        if (score>=best){
            best = score;
            bestName = names[nm];
        }
    }
}
System.out.println(bestName);
Eyal Schneider
ugh O(N^2) for something that should be O(1). Data structures people.
Byron Whitlock
What does the Int best = Integer.Min_value do
dalton
Eyal Schneider
@dalton: I initialize the variable *best* with the smallest possible integer. This way I guarantee that the first score encountered in the double loop will override it and set the corresponding name as well. Any other initialization value may cause the loop to terminate with bestName == null
Eyal Schneider
Integer.Min_Value returns the smallest possible value of int. In this case, it initializes the best score variable with the minimum value of int. You could initialize best with 0, but the answerer doesn't know if negative scores are going to be in your array, which would return the wrong answer. The minimum value of int is negative 2^16.
Josh Smeaton
@Josh: actually the minimum value of int is -2^31. Ints in Java are 32 bit.
Eyal Schneider
@Eyal maybe should have looked that up first hey. I figured int was 32bits wide, but would be -2^16 to + 2^16. Unless it was unsigned which would be +2^32. But no, I'm wrong.
Josh Smeaton