MMMMMCK
MMMMMCK

Reputation: 337

Finding Maximum Height and Width for 2D Array of Unknown Dimensions (Java)

In Java, I'd like to get the maximum element from both dimensions of a simple image array, ie:

int getWidth(Color[][] pixels){
    //return max of dimension 1
}

int getHeight(Color[][] pixels){
    //return max of dimension 2
}

I know how to do this for a 1D array in Java, I would just run a for loop with the condition of i < pixels.length. However, I'm not quite sure how .length works for a 2D array, or even if it does work. How would I approach this?

Upvotes: 0

Views: 1219

Answers (2)

swapnil
swapnil

Reputation: 230

If we consider 2D array they it is an array holding references to other arrays. If we consider matrix like this:

{
    {1,2,3},
    {4,6},
    {7,7,8,9}
}

So height for above matrix is 3 = no. of rows.

Width of matrix is 4 = Max(no. of element in each array).

int getHeight(Color[][] pixels) {
    return pixels.length;
}

int getWidth(Color[][] pixels) {
    int maxCount = 0;
    int rows = pixels.length;
    for (int i = 0; i < rows; i++) {
        if (maxCount < pixels[i].length) {
            maxCount = pixels[i].length;
        }
    }
    return maxCount;
}

Upvotes: 0

toastrackengima
toastrackengima

Reputation: 8742

Will .length still work?

A 2D array is just simply an array, where the items in it are other arrays. Since .length works on a 1D array, it will surely work on all arrays - the amount of dimensions does not matter.

However, pixels.length gives you the length of the parent array - i.e. the array that contains all of the other arrays inside it. To get the length of the second dimension, you will have to get the length of the arrays inside it.

So, how do we get the length of the 2nd dimension?

We know that all of these arrays must be the same length, so we use the one at position 0 only because it is the only one that we can be 100% sure will always exist - an array should always have at least one element.

Then, we just get the length of that array - pixels[0].length.

Upvotes: 1

Related Questions