java多维数组转置

时间:2011-12-07 20:55:19

标签: java arrays

我有一个基于行的多维数组:

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

我想将此数组转换为基于列的数组,如下所示:

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

......但我真的不知道从哪里开始

11 个答案:

答案 0 :(得分:12)

我看到所有答案都会创建一个新的结果矩阵。这很简单:matrix[i][j] = matrix[j][i];但是,如果是方形矩阵,您也可以就地执行此操作。

// Transpose, where m == n
for(int i = 0; i < m; i++) {
  for(int j = i+1; j < n; j++) {
    int temp = matrix[i][j];
    matrix[i][j] = matrix[j][i];
    matrix[j][i] = temp;
  }
}

这对于较大的矩阵更好,在这种矩阵中,创建新的结果矩阵在内存方面是浪费的。如果它不是正方形,您可以创建一个具有NxM维度的新方法并执行不合适的方法。注意:对于就地,请注意j = i + 1;它不是0。

答案 1 :(得分:10)

试试这个:

@Test
    public void transpose() {

        final int[][] original = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        for (int i = 0; i < original.length; i++) {
            for (int j = 0; j < original[i].length; j++) {
                System.out.print(original[i][j] + " ");
            }
            System.out.print("\n");
        }
        System.out.print("\n\n matrix transpose:\n");
        // transpose
        if (original.length > 0) {
            for (int i = 0; i < original[0].length; i++) {
                for (int j = 0; j < original.length; j++) {
                    System.out.print(original[j][i] + " ");
                }
                System.out.print("\n");
            }
        }
    }

输出:

1 2 3 4 
5 6 7 8 
9 10 11 12 


 matrix transpose:
1 5 9 
2 6 10 
3 7 11 
4 8 12 

答案 2 :(得分:4)

我正在挖掘这个帖子,因为我没有在答案中找到一个有效的解决方案,因此我会发布一个来帮助搜索一个人的人:

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

你应该通过以下方式调用它:

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

将按预期输出:

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

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

答案 3 :(得分:3)

更通用的方式:

/**
 * Transposes the given array, swapping rows with columns. The given array might contain arrays as elements that are
 * not all of the same length. The returned array will have {@code null} values at those places.
 * 
 * @param <T>
 *            the type of the array
 * 
 * @param array
 *            the array
 * 
 * @return the transposed array
 * 
 * @throws NullPointerException
 *             if the given array is {@code null}
 */
public static <T> T[][] transpose(final T[][] array) {
    Objects.requireNonNull(array);
    // get y count
    final int yCount = Arrays.stream(array).mapToInt(a -> a.length).max().orElse(0);
    final int xCount = array.length;
    final Class<?> componentType = array.getClass().getComponentType().getComponentType();
    @SuppressWarnings("unchecked")
    final T[][] newArray = (T[][]) Array.newInstance(componentType, yCount, xCount);
    for (int x = 0; x < xCount; x++) {
        for (int y = 0; y < yCount; y++) {
            if (array[x] == null || y >= array[x].length) break;
            newArray[y][x] = array[x][y];
        }
    }
    return newArray;
}

答案 4 :(得分:1)

如果你想进行矩阵的转置(在这种情况下为row count = col count),你可以这样跟随Java

public static void inPlaceTranspose(int [][] matrix){

    int rows = matrix.length;
    int cols = matrix[0].length;

    for(int i=0;i<rows;i++){
        for(int j=i+1;j<cols;j++){
            matrix[i][j] = matrix[i][j] + matrix[j][i];
            matrix[j][i] = matrix[i][j] - matrix[j][i];
            matrix[i][j] = matrix[i][j] - matrix[j][i];
        }
    }
}

答案 5 :(得分:0)

import java.util.Arrays;
import java.util.Scanner;

public class Demo {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int rows = askArray("Enter number of rows :", input);//asking number of rows from user

        int columns = askArray("Enter number of columns :", input);//asking number of columns from user
        int[][] array = Array(rows, columns, input);
        DisplayArray(array, rows, columns);//displaying initial matrix
        System.out.println("Transpose array ");
        int[][] array2=TransposeArray(array, rows,columns );//calling Transpose array method
        for (int i = 0; i < array[0].length; i++) {
            System.out.println(Arrays.toString(array2[i]));
        }

    }
    //method to take number of rows and number of columns from the user
    public static int askArray(String s, Scanner in) {
        System.out.print(s);
        int value = in.nextInt();

        return value;
    }
    //feeding elements to the matrix
    public static int[][] Array(int x, int y, Scanner input) {
        int[][] array = new int[x][y];
        for (int j = 0; j < x; j++) {
            System.out.print("Enter row number " + (j + 1) + ":");
            for (int i = 0; i < y; i++) {
                array[j][i] = input.nextInt();
            }

        }

        return array;
    }
    //Method to display initial matrix
    public static void DisplayArray(int[][] arra, int x, int y) {

        for (int i = 0; i < x; i++) {
            System.out.println(Arrays.toString(arra[i]));
        }
    }
    //Method to transpose matrix
    public static int[][] TransposeArray(int[][] arr,int x,int y){
        int[][] Transpose_Array= new int [y][x];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j <y ; j++) {
                Transpose_Array[j][i]=arr[i][j];
            }
        }

        return Transpose_Array;
    }
}

答案 6 :(得分:0)

       public int[][] getTranspose() {
            int[][] transpose = new int[row][column];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < column; j++) {
                    transpose[i][j] = original[j][i];
                }
            }
            return transpose;
        }

答案 7 :(得分:0)

使用此函数(如有必要,用int替换String)。它以矩阵作为字符串数组,并返回一个新的矩阵,即转置矩阵。它也检查空数组的边缘情况。没有照片。

/// Complete
private void issueBWworker_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        //toolStripStatusLabel1.Text = "Cancelled by User Intentionally...";
        pbar.Value = 0;
        pbar.Visible = false;
    }
    // Check to see if an error occurred in the background process.
    else if (e.Error != null)
    {
        //toolStripStatusLabel1.Text = e.Error.Message;
        pbar.Visible = false;
    }
    else
    {
        // BackGround Task Completed with out Error
        pbar.Visible = false;
        //toolStripStatusLabel1.Text = " All Records Loaded...";
    }
}

答案 8 :(得分:0)

这是我的50美分:用于转换多维数组的实用方法和测试(在我的情况下为双精度):

/**
  * Transponse bidimensional array.
  *
  * @param original Original table.
  * @return Transponsed.
  */
public static double[][] transponse(double[][] original) {

double[][] transponsed = new double
    [original[0].length]
    [original.length];

  for (int i = 0; i < original[0].length; i++) {

    for (int j = 0; j < original.length; j++) {

      transponsed[i][j] = original[j][i];
    }
  }

  return transponsed;
}


@Test
void aMatrix_OfTwoDimensions_ToBeTransponsed() {

  final double[][] original =
    new double[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };

  double[][] transponsed = Analysis.transponse(original);

  assertThat(transponsed[1][2], is(equalTo(10)));
}

答案 9 :(得分:-1)

public int[][] tiles, temp;

// Add values to tiles, wherever you end up doing that, then:
System.arraycopy(tiles, 0, temp, 0, tiles.length);

for(int row = 0; row < tiles.length; row++) // Loop over rows
  for(int col = 0; col < tiles[row].length; col++) // Loop over columns
    tiles[col][row] = temp[row][col]; // Rotate

那应该为你做。

答案 10 :(得分:-1)

import java.util.*;

public class TestClass {

    public static void main(String args[] ) throws Exception {

        Scanner in=new Scanner(System.in);

        int isize=in.nextInt();
        int jsize=in.nextInt();
        int arr[][]=new int[isize][jsize];
        int array[][]=new int[jsize][isize];
        for(int i=0;i<isize;i++) {
            for(int j=0;j<jsize;j++) {
                arr[i][j]=in.nextInt();
            }
            System.out.println("\n");
        }

        for(int n=0;n<arr[0].length;n++) {
            for(int m=0;m<arr.length;m++) {
                array[n][m]=arr[m][n];
                System.out.print(array[n][m]+" ");
            }
            System.out.print("\n");
        }
    }
}