Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating one dimension array as two dimension array

Tags:

java

arrays

I have,

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

as shown here, we create the the two dimensional one from the origin. But how do I iterate my oneDim inside for (index = 0; index < 10; index++) so that I could get my column index and row index there without creating a new one? I want it looks like this while printing its indexes to a two dimensional array (2x5):

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

I think the main issue here is getting the column index and row index without creating the two dimensional one. Don't you?

like image 514
van_tomiko Avatar asked Nov 30 '09 02:11

van_tomiko


2 Answers

The two numbers you're showing could be computed, in the order you're showing them in, as index/2 and index%2 respectively. Is that what you mean by "the issue"?

like image 153
Alex Martelli Avatar answered Sep 17 '22 14:09

Alex Martelli


If you want row-major order, given row rowIndex, column columnIndex and are faking (for lack of a better term) a two-dimensional array with numberOfColumns columns, the formula is

rowIndex * numberOfColumns + columnIndex.

If you want row-major order, given row rowIndex, column columnIndex and are faking (for lack of a better term) a two-dimensional array with numberOfRow rows, the formula is

columnIndex * numberOfRows + rowIndex.

So, assuming row-major order:

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]);
    }
}

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 indexing using a single for loop, assuming row-major order, the formula that you want is the following:

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

If you're using column-major order, the formula that you want is the following:

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

So,

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]);
}

will 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

as expected.

like image 39
jason Avatar answered Sep 19 '22 14:09

jason