Search for specific rows in a multidimensional array

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 will look for a two-dimensional array and compare the numbers of the 2-D array with the input number ... and so:

private static int [] searchArray (int [] [] num, int N) {

Now the part we are returning is a new one-dimensional array indicating the index of the first number in each row, which is greater than the variable of N. If the number is not greater than N, then -1 is returned for this position of the array.

So, for example, a multidimensional array named "A":

4 5 6

8 3 1

7 8 9

2 0 4

If we used this method and searched Array (A, 5), the answer would be "{2,0,0, -1)"

+4
source share
2 answers

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 (one with a for inside it) intersects the 2D array from top to bottom in a left to right direction. This is, firstly, this is with 4, then 5,6,8,3,1,7,8,9.

First, an array of results is created. The length depends on the number of lines num. the result [i] is set to -1 if the number is not greater than N. if the number is greater than N is found, the column index is saved as the result [i] = j, and a gap 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.

+1
source

As a rule, when using multidimensional arrays, you are going to use a nested 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 will not give you more than the basic structure, because you need to understand the question; you will encounter such structures in the future, but this should make you start.

0
source

All Articles