❌

Reading view

There are new articles available, click to refresh the page.

2D Matrix Addition, Multiplication, Largest in EachRow, Is Descending Order

package taskPkg;

public class MatrixCalc {
	public static void main(String[] args) {
		// 1. MATRIX ADDITION ( A + B )
		// 2. MATRIX MULTIPLICATION ( C*D ) IF C is nxk AND D IS kxm RESULTANT MUST BE
		// nxm
		int[][] A = { { 4, 2, 5 }, { 6, 3, 4 }, { 8, 1, 2 } };
		int[][] B = { { 5, 1, 3 }, { 2, 3, 2 }, { 1, 6, 4 } };
		int[][] C = { { 4, 2 }, { 2, 1 }, { 5, 3 } };
		int[][] D = { { 1, 2, 3 }, { 3, 2, 5 } };
		int[] desc = { 9, 5, 2, 1 };
		int[][] M = new int[C.length][D[0].length];

		MatrixCalc matOp = new MatrixCalc();
		matOp.add(A, B);
		System.out.println("-------------------------");
		matOp.multiply(C, D, M);
		System.out.println("-------------------------");
		matOp.LargestInEachRow(M);
		System.out.println("-------------------------");
		matOp.isDescendingOrder(desc);
	}

	private void add(int[][] A, int[][] B) {
		int r = A.length, c = A[0].length;
		int[][] S = new int[r][c];
		for (int i = 0; i < r; i++) {
			for (int j = 0; j < c; j++) {
				S[i][j] = A[i][j] + B[i][j];
			}
		}
		print2Darray(A, "A");
		print2Darray(B, "B");
		System.out.println("SUM : S = A+B");
		print2Darray(S, "S");
		System.out.println();
	}

	private void multiply(int[][] C, int[][] D, int[][] M) {
		int n = C.length, q = D.length, m = D[0].length;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				for (int k = 0; k < q; k++) {
					M[i][j] += C[i][k] * D[k][j];
				}
			}
		}
		print2Darray(C, "C");
		print2Darray(D, "D");
		System.out.println("MULTIPLY : M = CxD");
		print2Darray(M, "M");
	}

	private void LargestInEachRow(int[][] M) {
		int L[] = new int[M.length];
		System.out.println("LARGEST IN EACH ROW OF : M ");
		System.out.print("[");
		for (int i = 0; i < M.length; i++) {
			L[i] = M[i][0];
			for (int j = 0; j < M[0].length; j++) {
				L[i] = L[i] < M[i][j] ? M[i][j] : L[i];
			}
			System.out.print(" " + L[i] + " ");
		}
		System.out.println("]");
	}

	private void isDescendingOrder(int[] des) {
		boolean desc = true;
		System.out.print("Array des [");
		for (int i = 0; i < des.length; i++) {
			System.out.print(" " + des[i] + " ");
			if (i > 0 && desc && des[i - 1] < des[i])
				desc = false;
		}
		System.out.println("]");
		if (desc)
			System.out.println("Given Array des is In Descending Order");
		else
			System.out.println("Given Array des is NOT In Descending Order");
	}

	private void print2Darray(int[][] ar, String arName) {
		System.out.print("Array " + arName + " : ");
		for (int i = 0; i < ar.length; i++) {
			if (i > 0)
				System.out.print("          ");
			System.out.print("[");
			for (int j = 0; j < ar[0].length; j++) {
				System.out.print(" " + ar[i][j] + " ");
			}
			System.out.println("]");
		}
		System.out.println();
	}

}

OUTPUT:

❌