-
Notifications
You must be signed in to change notification settings - Fork 7
/
matrix.java
98 lines (85 loc) · 2.7 KB
/
matrix.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Scanner;
public class MatrixSort
{
public static void main() {
MatrixSort ob=new MatrixSort();
Scanner in = new Scanner(System.in);
System.out.print("ENTER MATRIX SIZE (M): ");
int m = in.nextInt();
if (m <= 3 || m >= 10) {
System.out.println("THE MATRIX SIZE IS OUT OF RANGE.");
return;
}
int a[][] = new int[m][m];
System.out.println("ENTER ELEMENTS OF MATRIX");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ROW " + (i+1) + ":");
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
/*
* Only positive integers
* should be enetered
*/
if (a[i][j] < 0) {
System.out.println("INVALID INPUT");
return;
}
}
}
System.out.println("ORIGINAL MATRIX");
ob.printMatrix(a, m);
ob.sortNonBoundaryMatrix(a, m);
System.out.println("REARRANGED MATRIX");
ob.printMatrix(a, m);
ob.computePrintDiagonalSum(a, m);
}
public void sortNonBoundaryMatrix(int a[][], int m) {
int b[] = new int[(m - 2) * (m - 2)];
int k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
b[k++] = a[i][j];
}
}
for (int i = 0; i < k - 1; i++) {
for (int j = 0; j < k - i - 1; j++) {
if (b[j] > b[j + 1]) {
int t = b[j];
b[j] = b[j+1];
b[j+1] = t;
}
}
}
k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
a[i][j] = b[k++];
}
}
}
public void computePrintDiagonalSum(int a[][], int m) {
int sum = 0;
System.out.println("DIAGONAL ELEMENTS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (i == j || i + j == m - 1) {
sum += a[i][j];
System.out.print(a[i][j] + "\t");
}
else {
System.out.print("\t");
}
}
System.out.println();
}
System.out.println("SUM OF THE DIAGONAL ELEMENTS = " + sum);
}
public void printMatrix(int a[][], int m) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}