將Array的 由橫向變成縱向(相反亦同)。
Ex:
5 6 7 8
9 10 11 12
變成
1 5 9
2 6 10
3 7 11
4 8 12
範例程式碼如下:
範例程式碼如下:
public class Testtranspose { public static void main(String[] args) { 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"); } int[][] tranposeArray=transpose(original) ; 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"); } } public static int[][] transpose(int[][] original) { int[][] transposeArray=new int[original[0].length][original.length]; 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++) { transposeArray[i][j]=original[j][i]; } } } return transposeArray; } }
參考資料來源:
http://stackoverflow.com/questions/8422374/java-multi-dimensional-array-transposing
沒有留言:
張貼留言