如果要以行为主的顺序,给定row
rowIndex,column
columnIndex并且伪造(缺乏更好的术语)带有
numberOfColumns列的二维数组,则公式为
rowIndex * numberOfColumns + columnIndex.
如果要以行为主的顺序,给定row
rowIndex,column
columnIndex和伪造(缺少更好的术语)带有
numberOfRow行的二维数组,则公式为
columnIndex * numberOfRows + rowIndex.
因此,假设行顺序为:
int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int rows = 2;int columns = 5;for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { System.out.println(row + ", " + column + ": " + oneDim[row * columns + column]); }}
输出:
0, 0: 10, 1: 20, 2: 30, 3: 40, 4: 51, 0: 61, 1: 71, 2: 81, 3: 91, 4: 10
并且如果您坚持使用单循环进行索引
for(假设行优先),则所需的公式如下:
int column = index % numberOfColumns;int row = (index - column) / numberOfColumns;
如果您使用的是列优先顺序,则所需的公式如下:
int row = index % numberOfRows;int column = (index - row) / numberOfRows;
所以,
int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int rows = 2;int columns = 5;for(int index = 0; index < 10; index++) { int column = index % columns; int row = (index - column) / columns; System.out.println(row + ", " + column + ": " + oneDim[index]);}
将输出
0, 0: 10, 1: 20, 2: 30, 3: 40, 4: 51, 0: 61, 1: 71, 2: 81, 3: 91, 4: 10
如预期的那样。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)