如果您想使用行主序,给定行索引 rowIndex、列索引 columnIndex 并且使用 numberOfColumns 列伪造(缺乏更好的术语)二维数组,公式如下:
rowIndex * numberOfColumns + columnIndex.
如果您想使用行优先顺序,给定行索引
rowIndex
,列索引
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: 1
0, 1: 2
0, 2: 3
0, 3: 4
0, 4: 5
1, 0: 6
1, 1: 7
1, 2: 8
1, 3: 9
1, 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: 1
0, 1: 2
0, 2: 3
0, 3: 4
0, 4: 5
1, 0: 6
1, 1: 7
1, 2: 8
1, 3: 9
1, 4: 10
如预期。