Search code examples
language-agnostic

How to calculate index from row and column?


I want to calculate an index (base 0) for any given row and column where rows and columns are base 1 and the number of columns is known, e.g. 2

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

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

To calculate column number from index

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

Question is how to calculate row and column from any index where the index is base 0. This is to calculate an index into an array in a java application.

The correct solution for me as supplied by 'Willem Van Onsem':

Where 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

Solution

  • Given every row consists out of n columns, the zero-based index for the column and row are:

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

    Now since your row and col are offset 1, you simply add 1 to both:

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

    For the inverse function, if row and col are offset 0, you can calculate the index as:

    int index = row*n+col;
    

    or if the indexes are offset 1:

    int index = row1*n+col1-n-1;