java multi-dimensional array transposing

后端 未结 11 2178
谎友^
谎友^ 2020-12-10 11:42

I have a row-based multidimensional array:

/** [row][column]. */
public int[][] tiles;

I would like to transform this array to column-based

11条回答
  •  萌比男神i
    2020-12-10 12:21

    I´m just digging this thread up because i did not find a working solution in the answers, therefore i will post one to help anyone who searches for one:

    public int[][] transpose (int[][] array) {
      if (array == null || array.length == 0)//empty or unset array, nothing do to here
        return array;
    
      int width = array.length;
      int height = array[0].length;
    
      int[][] array_new = new int[height][width];
    
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          array_new[y][x] = array[x][y];
        }
      }
      return array_new;
    }
    

    you should call it for example via:

    int[][] a = new int[][] {{1,2,3,4},{5,6,7,8}};
    for (int i = 0; i < a.length; i++) {
      System.out.print("[");
      for (int y = 0; y < a[0].length; y++) {
        System.out.print(a[i][y] + ",");
      }
      System.out.print("]\n");
    }
    
    a = transpose(a); // call
    System.out.println("");
    
    for (int i = 0; i < a.length; i++) {
      System.out.print("[");
      for (int y = 0; y < a[0].length; y++) {
        System.out.print(a[i][y] + ",");
      }
      System.out.print("]\n");
    } 
    

    which will as expected output:

    [1,2,3,4,]
    [5,6,7,8,]
    
    [1,5,]
    [2,6,]
    [3,7,]
    [4,8,]
    

提交回复
热议问题