Operations on matrix with no defined size

Asked

Viewed 408 times

5

I need to perform operations on a matrix that will be passed by parameter, the problem is that its size is not fixed so I do not know how to perform the loop to go through the end of a column or row for example.

private static void calcularMatriz(int[][] matriz, int linha) {
        int soma = 0;
        // soma os valores em linha
        for (int i = 0; i < ??; i++) {
            System.out.println(matriz[linha][i]);
        }
}

1 answer

5


Vectors are objects in java as well as matrices. This means that there are methods and attributes that you can use. One of these attributes stores the size of the vector and is called length.

Let’s assume you have the following matrix:

int[][] matriz = new int[3][4];

To traverse it, you can use the following algorithm: (Just as an example, each position of the matrix is being filled with the value of i,j currents).

for (int i = 0; i < matriz.length; i++)
    for (int j = 0; j < matriz[i].length; j++)
        matriz[i][j] = i + j;

To print, therefore, just do:

for (int i = 0; i < matriz.length; i++)
    for (int j = 0; j < matriz[i].length; j++)
        System.out.println(i + "," + j + "=" + a[i][j]);

So, to make it clearer, see that to go through the lines is used:

matriz.length

To scroll through the columns:

matriz[i].lenght

where i is the index of the row you want to go through each column.

Important note

This way of going through above seems unnecessary, since for every row there is always the same number of columns. So someone could do this algorithm as follows:

int linhas = matriz.lenght;
int colunas = matriz[0].length;

for (int i = 0; i < linhas; i++)
    for (int j = 0; j < colunas; j++)
        matriz[i][j] = i + j;

It is OK to do this if the matrix is always rectangular. However, consider the case below, taken from (https://stackoverflow.com/a/4000217/2236741)

int[][] matrizIrregular = new int[][] {
    new int[] { 1, 2, 3 },
    new int[] { 1, 2, 3, 4},
};

For this case, the way to go is the first exposed, that is, it will be necessary to know the size for each line traveled. So, in my opinion, it is best to do it in a way that meets any kind of situation. Therefore, the way below is the most indicated.

for (int i = 0; i < matrizIrregular.length; i++)
    for (int j = 0; j < matrizIrregular[i].length; j++)
        matriz[i][j] = i + j;
  • 1

    It was faster, +1.

  • 1

    Like in the wild west. :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.