簡體   English   中英

多維數組轉置

[英]Multi-dimensional array transposing

我有一個基於行的多維數組:

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

我想將此數組轉換為基於列的數組,如下所示:

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

......但我真的不知道從哪里開始

我看到所有答案都創建了一個新的結果矩陣。 這很簡單:

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尺寸的新尺寸並執行NxM的方法。 注意:對於就地,請注意j = i + 1 它不是0

嘗試這個:

@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 

我只是在挖掘這個線程,因為我沒有在答案中找到有效的解決方案,因此我會發布一個來幫助任何搜索一個的人:

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

更通用的方式:

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

如果您想進行矩陣的就地轉置(在這種情況下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];
        }
    }
}
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;
    }
}
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;
}

使用此函數(如有必要,將 String 替換為 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;
}

這是我的 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)));
}

這是我大約一年前想出的,當時我只是剛剛學習,所以我在學習 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-loop以遞增一個值直到列表的長度。 然后我們將這些和 go 存儲在數組范圍內以使其水平。

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

Output:

[[1, 2, 3, 4, 5, 6]]
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

那應該為你做。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM