Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Tuesday 5 February 2019

THIRD WEEK TERM WORK Program 1 (1b)

Question:

Write a Java program that uses threads to compute multiplication of two matrices. The program should perform multiplication of matrices of arbitrary order. Also, proper error
handling mechanism should be used.
Methodology: Matrix multiplication is implemented using the formula: Cij = Aik * Bkj.
This formula is used for generating each element of the final matrix. The multiplication must be performed by separate threads.

 Ex: If the order of the final matrix is 3X3, then a total of 9 threads should be created; each thread computing individual elements of the final matrix.

Solution:


import java.util.*;

class MatrixMultiple extends Thread {
Mutiple obj;

public MatrixMultiple(Mutiple obj) {
// TODO Auto-generated constructor stub
this.obj = obj;
}

void run(int i, int j, int m) {
obj.multiple(i, j, m);
}
}

public class firstProgram {
static int[][] mat1;
static int[][] mat2;
static int[][] matResult;

public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.println("Enter first Matrix index nXm");
int n = input.nextInt();
int m = input.nextInt();
System.out.println("Enter second Matrix index pXq");
int p = input.nextInt();
int q = input.nextInt();
if (n!= q) {
System.out.println("m is not p matrix Multiplication is not possible");
System.exit(-1);
}
mat1 = new int[n][m];
mat2 = new int[p][q];
matResult = new int[n][q];
System.out.println("Enter the values for first matrix");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat1[i][j] = input.nextInt();
}
}
System.out.println("Enter the values for Second matrix");
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
mat2[i][j] = input.nextInt();
}
}
Mutiple mul = new Mutiple();
int nt = n * q, k = 0;

MatrixMultiple obj[] = new MatrixMultiple[nt];
try {
for (int i = 0; i < n; i++) {
for (int j = 0; j < q; j++, k++) {
obj[k] = new MatrixMultiple(mul);
obj[k].start();
obj[k].run(i, j, m);
obj[k].join();

}

}
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("RESULT MATRIX");
for (int i = 0; i < n; i++) {
for (int j = 0; j < q; j++, k++) {
System.out.print(matResult[i][j] + " ");
}
System.out.println();
}
}
}

class Mutiple extends firstProgram {
public void multiple(int i, int j, int m) {
int sum = 0;
for (int y = 0; y < m; y++) {
sum = sum + mat1[i][y] * mat2[y][j];
}
matResult[i][j] = sum;
}
}


OUTPUT-:



Enter first Matrix index nXm
3
2
Enter second Matrix index pXq
2
3
Enter the values for first matrix
1
2
3
4
5
6
Enter the values for Second matrix
6
5
4
3
2
1
RESULT MATRIX
12 9 6 
30 23 16 

0 comments:

Post a Comment