Calculate index from row and column

I want to calculate the index (base 0) for each row and column, where the rows and columns are base 1 and the number of columns is known, for example 2

If max_columns is 2 and the index is 5, then to calculate the row number from the index:

    Row = (index % max_columns) + (int)(index / max_columns)
        = (5 % 2) + (int)(5 / 2)
        = 1 + 2
        = 3 

To calculate a column number from an index

    Col = max_columns - (index % max_columns)
        = 2 - (5 % 2)
        = 2 - 1
        = 1

The question is how to calculate the row and column from any index, where the index is base 0. This is for calculating the index into an array in a Java application.

The right solution for me, as stated in "Willem Van Onsem"

If Row is 3, Col is 2 and max_columns is 2:

    Index = (Row * max_columns) + Col - max_columns - 1
          = (3 * 2) + 2 - 2 - 1
          = 6 + (-1)
          = 5
+3
source share
2 answers

If each row consists of n columns, the index for the column and row based on zero is:

int row = index/n;
int col = index%n;

, row col 1, 1 :

int row1 = (index/n)+1;
int col1 = (index%n)+1;

, row col 0, :

int index = row*n+col;

1:

int index = row1*n+col1-n-1;
+2
row = (int) (index / max_columns + 1)
col = (index % max_columns + 1)
0

Source: https://habr.com/ru/post/1653819/


All Articles