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?
To get the number of columns of a 2D Numpy array, use its shape property. Here's a quick example. Suppose we have a 2 by 3 array: Join our newsletter for updates on new DS/ML comprehensive guides (spam-free) Did you find this page useful?
Example 2 : We can use the len () method to get the count of rows and columns. dataframe.axes [0] represents rows and dataframe.axes [1] represents columns. So, dataframe.axes [0] and dataframe.axes [1] gives the count of rows and columns respectively.
For an array in Java, we can get the length of the array with array_name.length. Similarly, how would one get the number of rows and columns of a 2D array? Show activity on this post. Well you probably want array_name.length for getting the count of the rows and array_name [0].length for the columns. That is, if you defined your array like so:
A naive approach is to iterate for every element in the array arr [] and for i th row do a linear search for every element in the array arr []. Count the number of elements and print the result for every row. An efficient approach is to iterate for all the elements in the i th row of the matrix. Mark all elements using a hash table.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With