Iterating one dimension array as two dimension array

后端 未结 3 998
[愿得一人]
[愿得一人] 2020-12-28 09:22

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.

相关标签:
3条回答
  • 2020-12-28 09:38

    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"?

    0 讨论(0)
  • 2020-12-28 09:57

    I think this is what your trying to do...convert a one-dim array into a two-dim array.

    //this is just pseudo code...not real syntax
    
    int[10] oneDim = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    int first_dim = 5;
    int second_dim = 2;
    
    int[first_dim][second_dim] new_array;
    
    for (int fdi = 0; fdi < first_dim; fdi++){
       for (int sdi = 0; sdi < second_dim; sdi++) {
    
          //this is the crux...you're calculating the one dimensional index to access the value
    
          new_array[fdi][sdi] = oneDim[fdi*second_dim + sdi] 
    
       }
    }
    
    0 讨论(0)
  • 2020-12-28 09:59

    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.

    0 讨论(0)
提交回复
热议问题