多维数组转置

22

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

/** [row][column]. */
public int[][] tiles;
我想将这个数组转换为基于列的数组,就像下面这样:
/** [column][row]. */
public int[][] tiles;

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

12个回答

17

我看到所有的答案都创建了一个新的结果矩阵。这很简单:

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 维度的新矩阵并使用 out-of-place 方法。注意:对于 in-place 方法,请确保 j = i + 1 而不是 0


为什么是 j + 1 而不是 0 呢?我猜这样可以避免冗余步骤,但在我像你一样初始化了 j 变量之后,我的代码开始工作了,除此之外我有相同的代码。 - Alfredo Gallegos
@AlfredoGallegos 如果你多做一些步骤,那么它不仅是“仅仅”冗余的,这意味着如果你交换两次,你基本上什么也没有交换。 - luk2302

11

以下解决方案实际上返回转置数组而不仅仅是打印它,并适用于所有矩形数组,而不仅仅是正方形。

public int[][] transpose(int[][] array) {
    // empty or unset array, nothing do to here
    if (array == null || array.length == 0)
        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,]

8

试一下这个:

@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 

6
这只是打印出了一个变化,实际上并没有改变数组。 - Jon Egeland
1
没有改变数组,只是展示循环的工作原理。 - Kent

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

1

如果你想进行矩阵的原地转置(在这种情况下,行数=列数),可以按以下方式使用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];
        }
    }
}

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

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        //asking number of rows from user
        int rows = askArray("Enter number of rows :", input);
        //asking number of columns from user
        int columns = askArray("Enter number of columns :", input);
        int[][] array = Array(rows, columns, input);
        //displaying initial matrix
        DisplayArray(array, rows, columns);
        System.out.println("Transpose array ");
        //calling Transpose array method
        int[][] array2 = TransposeArray(array, rows, columns);
        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;
    }
}

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

0
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

这应该对你有用。


2
那样行不通。你可能在想C或C++;在Java中,temp = tiles会使tilestemp成为同一个数组的引用,而你已经完全搞砸了它。:-P - ruakh
它出了什么问题?它无法编译吗?没有复制数组吗?是什么原因? - Jon Egeland
1
好的,它无法编译 - tmp 应该是 temp。然后,您从未实例化 temp(我假设 tiles 来自某些外部来源)。但即使修复了这些问题,它也会将 [[1, 2], [3, 4]] 转换为 [[1, 2], [2, 4]]。如果矩阵不是正方形而是矩形(即 N x M 而不是 N x N),它将抛出 ArrayIndexOutOfBoundsException。 - yshavit

0

这是我的建议:提供一个实用方法和测试来转置多维数组(在我的情况下是双精度):

/**
 * 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)));
}

0

这是我大约一年前想出来的,当时我刚开始学习编程,所以在学习Java两周后就想出了解决方案。

我们得到一个值列表:

int[] jest = new int[] {1, 2, 3, 4, 5, 6};

然后我们生成空的双重列表,获取单个列表的长度,并将它们存储在双重列表中。

int[][] storeValues = null;
int[][] valueLength = new int[jest.length][jest.length];
int[][] submit = null;
int[][] submitted = null;

创建一个双重循环来递增一个值,直到列表的长度。然后我们将这些存储起来,并遍历数组范围使其水平化。
for(int i=0; i<jest.length;i++) {
        for(int j = 0; j < jest.length;j++) {
      
        storeValues = new int[][] {jest};
     valueLength[j][i] = storeValues[0][i];
     
     submit = Arrays.copyOfRange(valueLength, 0, j+1);
     
     submitted = Arrays.copyOfRange(submit, j, j+1);
    }   

完整的工作代码:

import java.util.Arrays;

public class transMatrix {

    public static void main(String[] args) {
    int[] jest = new int[] {1, 2, 3, 4, 5, 6};
        int[][] storeValues = null;
        int[][] valueLength = new int[jest.length][jest.length];
        int[][] submit = null;
        int[][] submitted = null;
    for(int i=0; i<jest.length;i++) {
        for(int j = 0; j < jest.length;j++) {
      
        storeValues = new int[][] {jest};
     valueLength[j][i] = storeValues[0][i];
     
     submit = Arrays.copyOfRange(valueLength, 0, j+1);
     
     submitted = Arrays.copyOfRange(submit, j, j+1);
    }   
    
    }System.out.println(Arrays.deepToString(submitted)); 
}}

输出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接