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
source
share