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

Asked

Viewed 418 times

0

I was having some problems with array2D in c# so I decided to try using a normal array

(exemplo)

Suppose I have column 4 (red) and row 3 (blue), which is the formula for me to get the number that corresponds to them (22, green)?

  • 2

    What is the question? Where is the code? Should solve the problem you have in the correct tool for the problem, try to gambiarra makes you have 2 or more problems now.

  • @Maniero, I think he needs a code that locates the index of the number in the table using row and column.

  • 1

    Using a normal array when the information you have is 2d only creates more problems for you. Solve the problems you had in array2d and use the one that is most appropriate

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 the 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 number given 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, and so these formulas look like this:

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

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

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

celula = linha * largura + coluna

linha = celula / largura
coluna = celula % largura

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

In the 0-based format, each row corresponds to a cell block. The size of this block is the matrix width. Within the corresponding block, a number of cells equal to that of the columns is moved. That’s why to find the cell from the rows and columns the width value is multiplied by the row and the column value is summed.

Browser other questions tagged

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