Matrix operations with no set size

5

I need to perform operations on an array that will be passed by parameter, the problem is that its size is not fixed so I do not know how to loop to go to 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]);
        }
}
    
asked by anonymous 22.08.2015 / 23:46

1 answer

5

Vectors are objects in java as well as arrays. 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 .

Suppose you have the following array:

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

To run it, you can use the following algorithm: (Just as an example, each position of the array is filled with the value of i, j streams.)

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

To print, so 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 be 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 cycle through each column.

Important Note

This way of looking up seems unnecessary, since for every line there is always the same number of columns. So, one 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's okay to do this if the array is always rectangular. However, consider the case below, taken from ( link )

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

In this case, the way to go is the first one exposed, that is, it will be necessary to know the size for each line covered. So, in my opinion, it is best to do it in a way that suits any type of situation. So the way below is the right one.

for (int i = 0; i < matrizIrregular.length; i++)
    for (int j = 0; j < matrizIrregular[i].length; j++)
        matriz[i][j] = i + j;
    
22.08.2015 / 23:56