Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9d3e0cf

Browse files
committed
add matrix transpose
1 parent 1d82950 commit 9d3e0cf

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//package fromslides.S15;
2+
3+
/**
4+
* Create a 2d array, sum it
5+
*
6+
* @author pmc
7+
* @version slide deck 15
8+
*/
9+
10+
public class ArrayTranspose {
11+
public static void main(String[] args) {
12+
int[][] a = {
13+
{ 0,1,3,2 },
14+
{ 1,4,8,7},
15+
{ 9, 7,0,3 }
16+
};
17+
int[][] b = {
18+
{ 0,1,3,2 },
19+
{ 1,4,8,7, 5, 6 },
20+
{ 9, 7,0,3 }
21+
};
22+
int transposedArray[][];
23+
24+
transposedArray = transpose(a);
25+
displayArray("Original ", a);
26+
displayArray("Transposed ", transposedArray);
27+
28+
if (transposedArray == null)
29+
System.out.println("Original Array is not rectangular");
30+
else displayArray("Transposed ", transposedArray);
31+
32+
transposedArray = transpose(b);
33+
displayArray("Original ", b);
34+
35+
if (transposedArray == null)
36+
System.out.println("\nOriginal Array is not rectangular");
37+
else displayArray("Transposed ", transposedArray);
38+
39+
} // end main
40+
public static int[][] transpose (int[][] array) {
41+
//check if rectangular ​
42+
int col = array[0].length;
43+
for (int i = 1; i< array.length; i++)
44+
{
45+
if (array[i].length != col)
46+
return null;
47+
}
48+
// if we get here it must be rectangular so transpose​
49+
int[][] t = new int[array[0].length][array.length];
50+
for (int i = 0; i < t.length; i ++)
51+
{
52+
for (int j=0; j< t[i].length; j++)
53+
t[i][j] = array[j][i];
54+
}
55+
return t;
56+
}
57+
/**
58+
* display the array with a message
59+
* @param name message String integer array
60+
* @param arry integer array
61+
**/
62+
public static void displayArray(String name, int arry[]) {
63+
System.out.println("\nArray: "+name);
64+
for (int i=0; i < arry.length; i++)
65+
System.out.print("["+i+"] = "+ arry[i]+" ");
66+
}
67+
/**
68+
* display the array with a message
69+
* @param name message String integer array
70+
* @param arry integer array
71+
**/
72+
public static void displayArray(String name, int arry[][]) {
73+
System.out.println("\nArray: "+name);
74+
for (int row=0; row < arry.length; row++) {
75+
System.out.printf("[ ");
76+
for (int col = 0; col < arry[row].length; col++ )
77+
System.out.print(arry[row][col] +" ");
78+
System.out.printf("]\n");
79+
}
80+
}
81+
} // end class

0 commit comments

Comments
 (0)