Mou202020
Mou202020

Reputation: 31

print and count the maximun values in 2d array java

I have 2d array java, I need to look at it and check on the max value, then print it with the count of how many it is in the array

I was trying to do like this but it doesn't work

        int[][] rand = new int[][]{
                {1, 80, 3, 4, 5},
                {13, 199, 80, 8},
                {12, 22, 80, 190}
        };

        int max = rand[0][0];
        int count = 0;
        for (int i = 0; i < rand.length; i++){
            for (int ii = 0; ii < rand[i].length; ii++) {
                if (rand[i][ii] > max) {
                    max = rand[i][ii];
                    count++;
                }

            }
        }
        System.out.println(max + " " + count);

Upvotes: 3

Views: 95

Answers (2)

Eran
Eran

Reputation: 393771

You are not handling count correctly:

int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
    for (int ii = 0; ii < rand[i].length; ii++) {
        if (rand[i][ii] > max) {
            max = rand[i][ii];
            count = 1; // a new maximum's first occurrence
        } else if (rand[i][ii] == max) {
            count++; // another occurrence of the current maximum
        }
    }
}
System.out.println(max + " " + count);
  • When you find a new maximum, you should reset count to 1.

  • You should check if the current element is equal to the current maximum, and increment count if that's the case.

Output:

199 1

EDIT:

Fixed the case where the first element is the maximum. It turns out count should be initialized to 0 after all, since the loops re-visit the first element, so we don't want to count it twice if it's the maximum.

Upvotes: 2

A.Alexander
A.Alexander

Reputation: 598

You can use streams:

    int max = Arrays.stream(rand)
            .mapToInt(row -> Arrays.stream(row).max().getAsInt())
            .max().getAsInt();

    int count = Arrays.stream(rand)
            .mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
            .reduce(Integer::sum).getAsInt();

Upvotes: 0

Related Questions