Search code examples
javaarraysiterationnested-loopstranspose

Transposing a section of an int[][] type array in java


first post so apologies in advance for poor form. Im working on a project for my introductory java course where I need to transpose only a section of a larger array. In this particular case i've been given this array:

int[][] array = {{1, 2, 3, 4},{11, 12, 13, 14, 15, 16},{21, 22, 23, 24},{31, 32, 33}};

The method receives the input array, rowStart,rowEnd,colStart,colEnd params

so for example the input of the above array: transpose(array,0,3,1,2) should return an array that looks like {{2,12,22,32},{3,13,23,33}}

My intuition was to use a nested loop, one indexing the column#, and within that one indexing the row#, then taking these and moving them into the output array. I imagine this is possible, but im having a bit of trouble. Here's the code i've written and it's output for the example above:

public static int[][] transpose(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd) {
    int[][] newArray = new int[colEnd-colStart][rowEnd-rowStart];


    for (int i = colStart; i < colEnd; i ++ ){
      for(int j = rowStart; j < rowEnd; j ++){
        newArray[i-colStart][j-rowStart] = matrix[j][i];
      }
    }
   return newArray; 
  }

feeding it the array I gave at the start:

> int[][] array = {{1, 2, 3, 4}, {11, 12, 13, 14, 15, 16}, {21, 22, 23, 24}, {31, 32, 33}};
> Array2Lab.transpose(array, 0, 3, 1,2 )
{ { 2, 12, 22 } }

which is a fraction of the correct output.

Im still a little new to arrays, but my hunch is that i've either made the output array too small, or started/ended the index's at the wrong places.

Thanks for reading, any help greatly appreciated!

FIXED VERSION:

public static int[][] transpose(int[][] matrix, int rowStart, int rowEnd, int colStart, int colEnd) {
  int[][] newArray = new int[colEnd-colStart+1][rowEnd-rowStart+1];


    for (int i = colStart; i < colEnd+1; i ++ ){
      for(int j = rowStart; j < rowEnd+1; j ++){
        newArray[i-colStart][j-rowStart] = matrix[j][i];
      }
    }
   return newArray; 

Solution

  • Problem is with the upper value that you take for your counters:

    i < colEnd
    j < rowEnd
    

    You should include that upper value:

    i <= colEnd
    OR 
    i < colEnd + 1
    

    That explains why you retrieve only a sub part of your matrix