java多维数组转置

n3h0vuf2  于 2021-07-09  发布在  Java
关注(0)|答案(11)|浏览(463)

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

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

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

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

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

zu0ti5jz

zu0ti5jz1#

试试这个:

@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
c6ubokkw

c6ubokkw2#

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

那应该对你有用。

nvbavucw

nvbavucw3#

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

d4so4syb4#

使用此函数(如有必要,用int替换字符串)。它将矩阵作为字符串数组,并返回一个新的矩阵,即转置矩阵。它还检查空数组的边大小写。没有指纹。

private String[][] transposeTable(String[][] table) {
    // Transpose of empty table is empty table
    if (table.length < 1) {
        return table;
    }

    // Table isn't empty
    int nRows = table.length;
    int nCols = table[0].length;
    String[][] transpose = new String[nCols][nRows];

    // Do the transpose
    for (int i = 0; i < nRows; i++) {
        for (int j = 0; j < nCols; j++) {
            transpose[j][i] = table[i][j];
        }
    }

    return transpose;
}
axzmvihb

axzmvihb5#

这是我的50美分:一个实用的方法和测试转置多维数组(在我的例子中是double):

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

lx0bsm1f6#

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

yvfmudvl7#

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

b91juud38#

更一般的方式:

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

eit6fx6z9#

我只是在挖掘这个线索,因为我没有在答案中找到一个有效的解决方案,因此我将发布一个,以帮助任何人谁搜索一个:

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,]
ecbunoof

ecbunoof10#

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

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 .

hm2xizp9

hm2xizp911#

如果你想进行矩阵的原地转置(在这种情况下 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];
        }
    }
}

相关问题