I want the index of a cell, given the column and row numbers

0

I was having problems with array2D in C # so I decided to try to use a normal array

Suppose I have column 4 (red) and line 3 (blue), what is the formula for getting the number that corresponds to them (22, green)?

    
asked by anonymous 09.07.2018 / 05:48

1 answer

1

In the case of the first row, first column and first cell may have arbitrary values (not necessarily 0 or 1 and possibly different from each other), the general formula for finding the cell number based on the row number and column number is this:

celula = (linha - primeira_linha) * largura + (coluna - primeira_coluna) + primeira_celula

The inverse formulas, to find the row and column numbers from the cell number are these:

linha = (celula - primeira_celula) / largura + primeira_linha
coluna = (celula - primeira_celula) % largura + primeira_linha

In this case, the values primeira_linha , primeira_coluna and primeira_celula are, as the names indicate, the number given to the first row of the matrix (can be 1, 0, or any other value), the given number to the first column of the matrix and the number given to each individual cell. In your specific case, these three variables all have the value 1, so these formulas look like this:

celula = (linha - 1) * largura + (coluna - 1) + 1

linha = (celula - 1) / largura + 1
coluna = (celula - 1) % largura + 1

However, because in C # the arrays are indexed with the first element having index 0, it usually makes sense that these three variables have a value of 0, making the formulas there:

celula = linha * largura + coluna

linha = celula / largura
coluna = celula % largura

Note that the formula when the primeira_linha , primeira_coluna , and primeira_celula variables are zero is reasonably simpler. This is because the purpose of these variables in the formula is exactly to convert the arbitrary indexes of the first row, first column and first cell to the equivalent of when all of them are zeros.

In the format based on 0, each row corresponds to a block of cells. The size of this block is the width of the array. Within the corresponding block, you move a number of cells equal to the number of columns. That is why to find the cell from the rows and columns the width value is multiplied by the row and the column value is added.

    
09.07.2018 / 08:20