Java – iterates a one-dimensional array into a two-dimensional array

I have,

int[10] oneDim = {1,2,3,4,5,6,7,8,9,10},index = 0;

As shown in figure here, we create a two - dimensional from the origin But how can I iterate my onedim in (index = 0; index < 10; index) so that I can get my column index and row index without creating a new index? I want it to print its index like this into a two-dimensional array (2) × 5):

0,0
0,1
1,0
1,1
2,0
2,1
3,0
3,1
4,0
4,1

I think the main problem here is to get the column index and row index instead of creating a two-dimensional index isn't it?

Solution

If you want the row main order, give column rowindex, column columnindex, and forge (without a better term) a two-dimensional array with numberofcolumns column, the formula is

rowIndex * numberOfColumns + columnIndex.

If you want row main order, column columnindex and forge (lack of a better term) a two-dimensional array with numberofrow rows, the formula is

columnIndex * numberOfRows + rowIndex.

Therefore, assume that the row main sequence:

int[10] oneDim = {1,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]);
    }
}

Output:

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

And if you insist on using a single for loop for indexing, assuming row major order, the formula you want is as follows:

int column = index % numberOfColumns;
int row = (index - column) / numberOfColumns;

If you are using the primary column order, the formula you need is as follows:

int row = index % numberOfRows;
int column = (index - row) / numberOfRows;

So,

int[10] oneDim = {1,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]);
}

Will output

0,4: 10

As expected

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>