Habbo
Habbo

Reputation: 145

Java: Counting (and "removing") max-/minimum value of 2D array

I want the method to count all the maximum/minimum values in the 2D array poängInsamling. Each domare (=judge) gives a value to all deltagare (=members). I want to remove the maximum/minimum value of each deltagare. The code I have now only works if there are 2 or less members.

This is what I got:

        for (int x = 0; x < deltagare; x++) {
            for (int y = 0; y < domare; y++) {
                if (poängInsamling[y][x] == -1) {
                    poängInsamling[y][x] = 0;
                    break;
                }       
            }
        }
    return poängInsamling;
}

Thanks in advance, I've been trying to fix this for hours.

Edit: int[][]PoängInsamling = int[domare][deltagare];

If all deltagare has the same value, all their points end up 0.

Upvotes: 1

Views: 219

Answers (1)

Eran
Eran

Reputation: 394126

You are searching the entire 2D array in order to remove the lowest and highest value across all members, but you want to remove the lowest and highest value only for the current member. You can eliminate the second loop if you keep track of the index having the maximum/minimum value.

For example, for the maximum (the minimum will be similar) :

    int max = -1;
    int maxIndex = -1;
    for(int i = 0; i < deltagare; i++) {
        max = -1; // clear the max value when starting with a new member
        maxIndex = -1;
        for(int t = 0; t < domare; t++) {
            if (poängInsamling[t][i] > max) {
                max = poängInsamling[t][i];
                maxIndex = t;
            }       
        }
        // clear the max value for the current member
        poängInsamling[maxIndex][i] = -1;
    }

Upvotes: 1

Related Questions