How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);
Related
I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.
import java.util.Arrays;
public class main {
public static void main (String[] args ) {
int rand = (int)Math.random()*17;
int[][] output = array(rand);
//System.out.println(Arrays.deepToString(output));
}
public static int[][] array(int n) { //btw n is y/height
int x = (int)Math.pow(2, n-1); //# of col
int max = (int)Math.pow(2, n) - 1;
int [][] out = new int[n][x];
for (int i = 0; i < n; i++) {
for (int j = 0; j < x; j++) {
out[i][j] = (int) (Math.random() * (max + 1));
}
}
return out;
}
}
I'm learning how to code and a cousin gave me their old laptop and I found some small java files here and there. This one is called "itsmagic.java" but I don't really understand what the purpose is?
From what I understand it seems that we are creating a 2D array of some sort and then what? I understand that deepToString is supposed to be used to convert multidimensional arrays to strings, but how does that work? Why is it commented out?
What I understood from your code is:
-Pick a random int n from 0 to 17.
-setting a x = 2^(n-1)
-setting a max= 2^n
-Creating a double entry tab dimensions n*x
-Filling each case with a random number between 0 and max
So the result is a double entry tab of dimensions [0 to 17][2^(0 to 16)] filled with numbers between 0 and 2^(0 to 17)
Arrays.deepToString() is used for either single or multidimensional arrays, it's usually used for multidimensional arrays as it can clearly output each array.
You will be able to output both the first and second array of "output" in your example.
If you run a test and add in the array manually, you will see it prints both the arrays together instead of showing just the first dimension.
We are given some code snippets to look at and figure out what the code does/will do.
I understand methods and methods with arrays but I have never seen methodName(int[][] m) with two [][]
What does this mean? an array within an array?
int[][] in the method signature refers to a double array of integers. You can think of a double integer array as being a matrix of int values.
Taking your example 2D array:
int[][] in = {{2, 0, 2}, {3, 1, 2}, {1, 8, 4}};
This array has the following properties:
System.out.println(in.length); // prints 3 (number of arrays inside 'in')
System.out.println(in[0].length); // prints 3 (number of ints in first array)
System.out.println(in[1].length); // also prints 3 (number of ints in second array)
Here is a visual to show you how accessing this array works:
int a = 1;
int b = 0;
Then in[a][b] == in[1][0] == 3:
2 0 2
{3 1 2} <-- a = 1 (second subarray)
1 8 4
{3 1 2}
^-- b = 0 (first element in that subarray)
The first index a chooses the subarray, and the index b chooses the element inside the subarray.
It represents multi dimensional arrays (AKA arrays or arrays) of given data type.
Think hierarchical to understand it the best way.
If you have int[3][2], it means,
It holds value for each of the following index.
int[0][0]
int[0][1]
int[1][0]
int[1][1]
int[2][0]
int[2][1]
Hope it will help. I struggled a lot to understand it when i was a beginner.
Possible assign is
int[3][2] iValue = {{00,01}, {10,11}, {20, 21}}
Thanks for the correction.
methodName(int[] []) is an array of arrays. In response to all the comments, I tested it in eclipse and the length is 3.
In many programming languages (including Java), it is possible to create (and use) an array of arrays. In Java (specifically), all arrays are Object instances. Consider
Object intArray1 = new int[10];
Object intArray2 = new int[10];
Object intArray3 = new int[10];
Then you might have
Object[] arrs = { intArray1, intArray2, intArray3 };
or even
Object arrs = new Object[] { intArray1, intArray2, intArray3 };
JLS-15.10.1 Run-Time Evaluation of Array Creation Expressions says (in part)
Otherwise, if n DimExpr expressions appear, then array creation effectively executes a set of nested loops of depth n-1 to create the implied arrays of arrays.
A multidimensional array need not have arrays of the same length at each level.
Finally, there is Arrays.deepToString(Object[]) the Javadoc says (in part)
Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.
In Java, "int [ ][ ]" stands for a 2-dimensional integer array. To make it easy to understand, simply we can compare 2-d integer array with a simple 1-d integer array;
1) Down below, a 1-d int array is initialized;
int[] arr1d = { 1,2,3 };
2) And on this one, a 2-d int array is initialized;
int[][] arr2d = { {1,2,3}, {4,5,6} };
It is important to understand the structure of 2d arrays. If you print the length of the arr2d , you will get 2 the rows of the array which is 2.
System.out.println(arr2d[].length);
You will get the length of the outer array, which is actually row count of the array.
To get the inner array length, which is actually the column count;
System.out.println(arr2d[0].length);
Notice that we take the first row, and get the length of the inner array and print the column number.
To get familiar with the usage of the 2d array in a method, you can check this out;
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
In this static method, int[][] intArray is the only parameter which is obviously a 2 dimensional int array. There are two nested for loops to print the array as a matrix. The outer loop is traversing the rows and the inner loop is traversing on the inner loop.
Here is the complete example for the 2D Method usage;
public class Test2DArray {
public static void main(String[] args) {
//Init 2d integer list
int simpleArray[][] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
//Length of outer array which is actually Row Count;
System.out.println("Rows : " + simpleArray.length);
//Length of inner array which is actually Column Count;
//Notice that we take the first Row to get the Column length
System.out.println("Columns: " + simpleArray[0].length);
//Call the printIntegerList method with int[][] parameter
printIntegerArray(simpleArray);
}
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
}
And the output to the console is as below;
Rows : 3
Columns: 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
This is the question i am trying to solve:
Write a class called ArrayHistogram, which contains a main method and a static method called histogram, which has the following signature:
public static int[] histogram(int[][] arrayA)
In the main method, declare and initialize a two dimensional array, call it arrayA. This array must contain some non-negative integer numbers. The histogram method accepts arrayA and puts the frequency of occurrence of elements of arrayA into a one dimensional array (histA) and returns histA. Frequency of occurrence means, the number of times an element occurs in the array. Your program should work for a ragged array, as well. Your program should determine the size of the histA automatically, before declaring the variable histA.
Hint: Figure 1 shows a sample 2D array(arrayA) and the corresponding histA. histA[0] = 2 shows that 0 occurred twice in A. Or, histA[3] = 1, shows that number 3 appeared once in A.
I have done this so far
public class ArrayHistogram
{
public static void main (String[]args)
{
// declearing and initializing a 2D array.
int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
histogram(arrayA);
}
public static int[] histogram (int [][] arrayA)
{ // nested for loop to go through the array.
int max = 0;
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
if ( arrayA[row][col]> max ){
max = arrayA[row][col];
}
}
}
int histA[] = new int [max];
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
histA[arrayA[row][col]]++;
}
}
System.out.println(histA);
return histA;
}
}
This line:
histA[arrayA[row][col]]++;
shows a java.lang.ArrayIndexOutOfBoundsException
First am I doing this right?
If not how should I make it happen?
Keep in mind that arrays are indexed starting at 0, so your max value is not going to be an index available in your histA array. One way to fix this is create your array like so:
int histA[] = new int[max + 1];
In your second loop, when you hit row being 2 and col being 4 it's going to attempt to use histA[9] which isn't a valid index in that array unless you define your array to be of size 10, which in your case is max + 1.
length is an attribute of array objects which returns the size. Now since you are looping your array starting from 0 to the length of array, its referring to the index of array which doesn't even exists. Hence an ArrayIndexOutOfBoundException.
Just update your for loop termination expression to arrayA.length-1 and arrayA[row].length-1 and it will all be working fine.
Also for all such exceptions just check their Java Doc and you will get your answer.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.