-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_2D.java
More file actions
68 lines (63 loc) · 2.28 KB
/
Array_2D.java
File metadata and controls
68 lines (63 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class Array_2D {
public static void printMatrix(int matrix[][], String s) {
System.out.println(s + "Matrix : ");
for (int[] matrix1 : matrix) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix1[j] + " ");
}
System.out.println();
}
System.out.println();
}
public static int[][] randomMatrix(int n, int m) {
int randomMatrix[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// This is common way to write the {Math.random*(max-min+1)+ min} ;
randomMatrix[i][j] = (int) (Math.random() * (9 - 1 + 1)) + 1;
// randomMatrix[i][j] = 1;
}
}
return randomMatrix;
}
public static int[][] rotateMatrixClockwise(int matrix[][]) {
int n = matrix.length;
int m = matrix[0].length;
// Even though this block is commented then it will work but , if matrix is in
// same dimension then Time complexity is reduced and the space complexity
// {O(1)}
// if (n == m) {
// for (int i = 0; i < n; i++) {
// for (int j = i + 1; j < m; j++) {
// int temp = matrix[i][j];
// matrix[i][j] = matrix[j][i];
// matrix[j][i] = temp;
// }
// }
// return matrix;
// }
// // Till here the code can be commented
int TransposeMatrix[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
TransposeMatrix[i][j] = matrix[j][i];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = TransposeMatrix[i][j];
TransposeMatrix[i][j] = TransposeMatrix[i][n - 1 - j];
TransposeMatrix[i][n - 1 - j] = temp;
}
}
return TransposeMatrix;
}
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int matrix[][] = Genarate_Random.commonArray();
int TarnsposeMatrix[][] = rotateMatrixClockwise(matrix);
printMatrix(TarnsposeMatrix, "Transpose ");
}
}
}