#consistent need to traverse a multidimensional matrix

17 messages · Page 1 of 1 (latest)

blissful garnet
#

So I posted here a few days ago about having trouble with matrixes. My exam is going to focus heavily on matrixes and manipulation of them. One thing i'm particularly hitting a wall with is making sure I don't get out of bound errors when traversing a matrix. I know how to access the rows and columns of a matrix, but when needing to traverse a matrix in an unfamiliar order I get lost. One assignment wants me to traverse a matrix diagonally. Here is an example of a question that may be similar to what I am asked.

Given a two-dimensional array arr with dimensions MxN (M and N are not necessarily the same), you are
asked to write a method called flatten that will create and return a one-dimensional array based on arr
using the following scheme: only positive values from arr are kept and they are stored in the new one-
dimensional array sequentially, row-by-row. For example, with the following 3x4 array as input your method
should return the one-dimensional array also shown below. The original array should obviously remain intact.

rain stirrupBOT
#

This post has been reserved for your question.

Hey @blissful garnet! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

nocturne dawn
#

ok so regarding avoiding out of bounds errors, try making sure you are using simple for loops for iteration and don't modify the variables inside the loop

#

e.g.

for(int i=0;i<yourMatrix.length;i++){
  for(int j=0;j<yourMatrix[i].length;j++){
    System.out.println(yourMatrix[i][j];
  }
}
#

In here, I am using i with yourMatrix and i is only used for that

#

similarly, j is used with yourMatrix[i] and not in different contexts

#

make sure that the condition and the access match

#

and if you are doing things with the diagonal, you might want to use Math.min

#

e.g.

//print all elements on the main diagonal
if(yourMatrix.length>0){
  for(int i=0;i<Math.min(yourMatrix.length,yourMatrix[0].length);i++){
    System.out.println(yourMatrix[i][i]);//assumes rectangular array
  }
}
#

or alternatively, you could do the same thing like this:

for(int i=0;i<yourMatrix.length;i++){
  if(i<yourMatrix[i].length){
    System.out.println(yourMatrix[i][i]);//assumes rectangular array
  }
}
#

essentially make sure you are checking dimensions before accessing them

blissful garnet
#

hm

#

okay well

#

i also need to be able to traverse back up

#

that is another big part of the problem

#

some of the problems involve needing to check if there is a bound at that index and then traversing back up if not