16

I have a function which takes 2D array. I am wondering if there is anyway to get rows and columns of the 2D array without having to iterate on it. Method signature is not to be changes.

Function is inside the ninetyDegRotator class.

public static int [][] rotate(int [][] matrix){

    int [][] rotatedMatrix = new int[4][4];//need actual row n col count here
    return rotatedMatrix; //logic

}

And main code is

public static void main(String args[]){

    int [][] matrix = new int[][]{
            {1,2,3,4},
            {5,6,7,8},
            {9,0,1,2},
            {3,4,5,6}
    };

    System.out.println("length is " + matrix.length);
    int [][] rotatedMatrix = ninetyDegRotator.rotate(matrix);
} 

Also matrix.length gives me 4. So I guess it is number of rows that it gives meaning number of references in 1D array which themselves contain arrays. So is there a way to get the count without iterating?

0

2 Answers 2

57

If it's guaranteed that each row has the same length, just use:

int rows = matrix.length;
int cols = matrix[0].length;  // assuming rows >= 1

(In mathematics this is of course guaranteed, but it's quite possible in most languages to have an array of arrays, where the inner arrays are not all the same length).

Sign up to request clarification or add additional context in comments.

3 Comments

It seems to be guaranteed since rotation matrices are square matrices.
@ZouZou the OP appears to be misusing the term "rotate" to refer to manipulating the matrix itself rather than forming a rotation matrix.
Yeah it remains same. The program is actually for rotating matrix by 90deg. I guess I can use int [][] rotatedMatrix = new int[matrix.length][matrix[0].length]; Tx!
5
int row = mat.length;
int col= mat[0].length;

Mostly in array all row has same length. So above solution will work almost every time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.