QUESTION 3:
JAVA CODE
import java.util.*;
public class ISC2021Question3 {
public static void main(String[] args) {
int M,N;
Scanner in = new Scanner(System.in);
System.out.println("Enter the NUMBER OF ROWS of the matrix:");
M = in.nextInt();
System.out.println("Enter the NUMBER OF COLOUMNS of the matrix:");
N = in.nextInt();
while( M <=2 || N >= 8) {
System.out.println("OUT OF RANGE:");
System.out.println("Enter the NUMBER OF ROWS of the matrix:");
M = in.nextInt();
System.out.println("Enter the NUMBER OF COLOUMNS of the matrix:");
N = in.nextInt();
}
Matrix obj = new Matrix(M,N);
System.out.println("Enter the elements of the matrix:");
obj.inputMatrix();
System.out.println("ORIGINAL MATRIX:");
obj.originalMatrix();
System.out.println("REARRANGED MATRIX:");
obj.matrixSort();
in.close();
}
}
class Matrix{
public void originalMatrix() {
sumOFBoundaryElements(Mat);
}
public void matrixSort() {
int[] linearArray;
int counter=0;
linearArray = new int[row*coloumn];
//getting the elements of the 2D array in a single dimension array
for(int i=0;i<row;i++)
for(int j=0;j<coloumn;j++)
linearArray[counter++] = Mat[i][j];
//sorting the linear Array
for(int k = 0; k < counter-1;k++) {
for(int l = 0; l < counter-k-1; l++ ) {
if (linearArray[l+1] > linearArray[l]) {
int temp = linearArray[l+1];
linearArray[l+1] = linearArray[l];
linearArray[l] = temp;
}
}
}
// getting elements after sorting in the 2D Array
counter = 0;
for(int i=0;i<row;i++)
for(int j=0;j<coloumn;j++)
Mat[i][j] = linearArray[counter++];
// finding the sum of boundary elements of the Sorted Array
sumOFBoundaryElements(Mat);
}
private void sumOFBoundaryElements(int[][] X) {
sumOfBoundaryElements = 0;
for(int i=0;i<row;i++)
for(int j=0;j<coloumn;j++)
if(i== 0 || i == row-1 || j == 0 || j == coloumn-1)
sumOfBoundaryElements += X[i][j];
displayMatrix(Mat);
System.out.println("SUM OF BOUNDARY ELEMENTS:"+sumOfBoundaryElements);
}
/*private void displayMatrix(int[][] X) {
for(int i=0;i<row;i++) {
for(int j=0;j<coloumn;j++)
System.out.print(X[i][j]+" ");
System.out.println();
}
} */
// you can display the matrix by the method above
// but if you want to have a allined display use the method below
private void displayMatrix(int[][] X) {
int MAX_MATRIX=0;
for(int p=0;p<row;p++)
for(int q=0;q<coloumn;q++)
if(MAX_MATRIX < X[p][q])
MAX_MATRIX = X[p][q];
String s,element;
s=Integer.toString(MAX_MATRIX);
for(int i=0;i<row;i++) {
for(int j=0;j<coloumn;j++) {
element=Integer.toString(X[i][j]);
int tmp=element.length();
while(tmp !=s.length()) {
element +=" ";
tmp++;
}
System.out.print(element+" ");
}
System.out.println();
}
}
public void inputMatrix() {
Scanner in = new Scanner(System.in);
for(int i=0;i<row;i++)
for(int j=0;j<coloumn;j++)
Mat[i][j]=in.nextInt();
}
Matrix(int M, int N){
this.row = M;
this.coloumn = N;
Mat = new int[M][N];
sumOfBoundaryElements = 0;
}
private int row;
private int coloumn;
private int[][] Mat;
private int sumOfBoundaryElements;
}
No comments:
Post a Comment