here is the solution for Homework3 Worker class: public class Worker extends Thr
ID: 3547391 • Letter: H
Question
here is the solution for Homework3
Worker class:
public class Worker extends Thread {
int[][] A, B, C;
int row;
public Worker(int row, int[][] A, int[][] B, int[][] C) {
this.A =A; this.B = B; this.C = C; this.row = row;
}
public void run(){
for(int k=0; k<B[0].length;k++){
int sum=0;
for(int j=0;j<B.length;j++)
sum+=A[row][j]*B[j][k];
C[row][k]=sum;
}
}
}
Manager class:
public class Manager {
int[][] A, B, C;
public Manager(int m, int k, int n) {
A = new int[m][k];
B = new int[k][n];
C = new int[m][n];
//fill A and B
int item;
item =1;
for(int i=0;i<m;i++)
for(int j=0;j<k;j++)
A[i][j]=++item;
item=1;
for(int i=0;i<k;i++)
for(int j=0;j<n;j++)
B[i][j]=++item;
///Distribute the work
Worker[] w = new Worker[A.length];
for(int i=0;i<A.length;i++){
w[i] = new Worker(i, A, B, C);
w[i].start();
}
//wait for them all to finish
for(int i=0;i<A.length;i++){
try { w[i].join(); }
catch (InterruptedException e) {e.printStackTrace(); }
}
//print C
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.printf("%4d ",C[i][j]);
System.out.println();
}
}
public static void main(String[] args) {
new Manager(4,3,4);
}
}
The homework need to be done using p threads way for this solution
Explanation / Answer
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix ");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix ");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrix ");
scanf("%d%d", &p, &q);
if ( n != p )
printf("Matrices with entered orders can't be multiplied with each other. ");
else
{
printf("Enter the elements of second matrix ");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
scanf("%d", &second[c][d]);
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:- ");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
printf("%d ", multiply[c][d]);
printf(" ");
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.