I have a 2D array (int[][]) and switch between tracking of position in the matrix between a linear index and coordinates (row, column).
I have a method calculating the linear index from a row and column:
private int linearIndex(int r, int c){
return (r*columns) c;
}
where columns is the nr of columns in the matrix (3x4 matrix -> columns = 4)
I'm having troubles getting the row, column position from the linear index. My current approach is: row = linear index % rows column = linear index / columns
Where - once again - rows = total number of rows and columns = total number of columns
See above, issues arise on the first column when on a row > 0...
CodePudding user response:
Your approach for calculating the row and column from the linear index is almost correct. The issue arises because you are using the total number of columns instead of the total number of rows for the row calculation.
Here is one way you can calculate the row and column from the linear index:
int row = linearIndex / columns; int column = linearIndex % columns;
This approach works because the row is the integer division of the linear index by the number of columns, and the column is the remainder of the integer division of the linear index by the number of columns.
You can also calculate the row and column using the modulo operator instead of integer division, like this:
int row = linearIndex % (rows * columns) / columns;
int column = linearIndex % columns;
This approach works because the modulo operator returns the remainder of the division, and the remainder of the division of the linear index by the total number of cells in the matrix (rows * columns) is the same as the linear index of the cell in the first row. Then, we can calculate the row by taking the integer division of the result by the number of columns, and the column is the same as the result of the modulo operator.