Question

Hi, can someone please help me implement the transpose, multiply(Matrix b), multiply(Matrix m, int threads), and equals(Object in) methods? (This is Java) I really need help so please don't just refund the question.

public class Matrix {1 public int[] [] matrix; 1 int[] [] trans; 1 public int x, y; 1 private boolean transposed; 1 1 public//Do NOT modify this method public String toString(){1 String astring = 1:1 for(int row = 0; row < matrix.length; row++) {1 f

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the solution to your question. I tried my best to solve your doubt, however, if you find it is not as good as expected by you. Please do write your further doubts regarding this question in the comment section, I will try to resolve your doubts regarding the submitted solution as soon as possible.

Please give proper indentation as shown in the screenshot.

If you think, the solution provided by me is helpful to you please do an upvote.

1. 2. 3. 4. import java.io. Buffered Reader; import java.io.IOException; import java.util.List; import java.util.*; import ja
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.*; 
import java.io.FileReader;
import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors

class RowMultiplyWorker implements Runnable 
{

  private final int[][] result;
  private int[][] matrix1;
  private int[][] matrix2;
  private final int row;

  public RowMultiplyWorker(int[][] result, int[][] matrix1, int[][] matrix2, int row) {
  this.result = result;
  this.matrix1 = matrix1;
  this.matrix2 = matrix2;
  this.row = row;
 }
  @Override
  public void run() 
  {
    for (int i = 0; i < matrix2[0].length; i++) 
    {
      result[row][i] = 0;
      for (int j = 0; j < matrix1[row].length; j++) 
      {
        result[row][i] += matrix1[row][j] * matrix2[j][i];
      }
    }
  }  
}

public class Matrix 
{
  public int[][] matrix;
  int[][] trans;
  public int x,y;
  private boolean transposed;

  public Matrix(int x,int y)
  {
    matrix=new int[x][y];
    this.x=x;
    this.y=y;
  }

  // helper function
  public int getIJ(int i,int j)
  {
    return this.matrix[i][j];
  }

  private int[][] transpose(int[][] arr)
  {
    int[][] Mtrans=new int[arr[0].length][arr.length];
    for(int i=0;i<arr.length;i+=1)
    {
      for(int j=0;j<arr[0].length;j+=1)
      {
        Mtrans[j][i]=arr[i][j];
      }
    }
    return Mtrans;
  }

  public void set(int[][] in)
  {
    this.matrix=in;
  }
  

  public void load(String path) throws IOException
  {
    BufferedReader br=null;
    try 
    {
      br=new BufferedReader(new FileReader(path));
    }
    catch(FileNotFoundException e)
    {
      System.err.println("file not found: "+path);
    }

    int row=0;
    while(true)
    {
      String line = br.readLine();
      if(line == null)
      {
        break;
      }
      String arr[]=line.split(" ");
      for(int i=0;i<arr.length;i+=1)
      {
        matrix[row][i]=Integer.parseInt(arr[i]);
      }
      row+=1;
    }
    trans=transpose(matrix);
    transposed=true;
  }


  public String toString() 
  {
    String aString="";
    for(int row=0;row<matrix.length;row+=1)
    {
      for(int col=0;col<matrix[row].length;col+=1)
      {
        aString+=" "+matrix[row][col];
      }
      aString+="\r\n";
    }
    return aString;
  }


  public Matrix multiply(Matrix b)
  {
    if(b.x!=this.y)
    {
      System.err.println("Number of columns of Matrix is not equal to row of b!!!");
      return null;
    }
    else  
    {
      int[][] c=new int[this.x][b.y];
      for(int i=0;i<this.x;i++)
      {    
        for(int j=0;j<b.y;j++)
        {    
          c[i][j]=0;      
          for(int k=0;k<b.x;k++)      
          {      
            c[i][j]+=this.getIJ(i,k)*b.getIJ(k,j);      
          }
        }
      }
      Matrix nMatrix=new Matrix(this.x,b.y);
      nMatrix.set(c);
      return nMatrix;
    }
  }


  public Matrix multiply(Matrix m,int threadcnt)
  {
    List<Thread> threads = new ArrayList<>();
    int rows1 = this.x;
    int[][] result=new int[this.x][m.y];
    for (int i = 0; i < rows1; i++) 
    {
      RowMultiplyWorker task = new RowMultiplyWorker(result, this.matrix, m.matrix, i);
      Thread thread = new Thread(task);
      thread.start();
      threads.add(thread);
      if (threads.size() % threadcnt == 0) 
      {
        waitForThreads(threads);
      }
    }

    Matrix nMatrix=new Matrix(this.x,m.y);
    nMatrix.set(result);
    return nMatrix;
  }


  private static void waitForThreads(List<Thread> threads) 
  {
    for (Thread thread : threads) 
    {
      try 
      {
        thread.join();
      } 
      catch (InterruptedException e) 
      {
        e.printStackTrace();
      }
    }
    threads.clear();
  }
  
  public boolean equals(Matrix in)
  {
    if(this.x!=in.x && this.y!=in.y)
    {
      return false;
    }
    for(int i=0;i<this.x;i+=1)
    {
      for(int j=0;j<this.y;j+=1)
      {
        if(this.getIJ(i,j)!=in.getIJ(i,j))
        {
          return false;
        }
      }
    }
    return true;
  }

  
  public static void main(String[] args)
  {
    Matrix a=new Matrix(3,4);
    Matrix b=new Matrix(4,4);

    int[][] ain={
      {1,2,3,4},
      {1,2,3,4},
      {1,2,3,4}
    };

    int[][] bin={
      {1,2,3,4},
      {1,2,3,4},
      {1,2,3,4},
      {1,2,3,4}
    };

    a.set(ain);
    b.set(bin);

    Matrix rem=a.multiply(b,3);
    Matrix rem1=a.multiply(b);

    System.out.println(a);
    System.out.println("===========================\n");
    System.out.println(b);
    System.out.println("===========================\n");
    System.out.println(rem);
    System.out.println("===========================\n");
    System.out.println(rem1);
    System.out.println("===========================\n");

  }
}
> javac Matrix.java > java Matrix 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 10 20 30 40 10 20 30 40 10 20 30 40
Add a comment
Know the answer?
Add Answer to:
Hi, can someone please help me implement the transpose, multiply(Matrix b), multiply(Matrix m, int threads), and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /**...

    cant understand why my toString method wont work... public class Matrix { private int[][] matrix; /** * default constructor -- * Creates an matrix that has 2 rows and 2 columns */ public Matrix(int [][] m) { boolean valid = true; for(int r = 1; r < m.length && valid; r++) { if(m[r].length != m[0].length) valid = false; } if(valid) matrix = m; else matrix = null; } public String toString() { String output = "[ "; for (int i...

  • Hi i need heeeeelllllp on this assignment i need to print the numbers diagonal top right...

    Hi i need heeeeelllllp on this assignment i need to print the numbers diagonal top right corner to the bottom left corner and i dont know how to do it please help me thank you dd another method to the bottom of the "TwoDimArraysMethods.java" file called "printDiagonalRL()"                                         public static void printDiagonalRL(int[][] matrix) 4. Call this method in the main file ("TwoDimArraysAsParam.java") passing it "board." e.g. TwoDimArraysMethods.printDiagonal(board); 5. Your new method should print any numbers along the diagonal from...

  • Consider the following matrix transpose routines: typedef int array[4][4]; void transpose (array dst, array src) {...

    Consider the following matrix transpose routines: typedef int array[4][4]; void transpose (array dst, array src) {     int i, j;     for (i=0; i<4; i++) {    for (j=0; j<4; j++) {           dst[i][j] = src[i][j];    }     } } void transpose2 (array dst, array src) {     int i, j;     for (i=0; i<4; i++) {    for (j=0; j<4; j++) {           dst[j][i] = src[j][i];    }     } } Assume this code runs on...

  • Java 1. Write a getCount method in the IntArrayWorker class that returns the count of the...

    Java 1. Write a getCount method in the IntArrayWorker class that returns the count of the number of times a passed integer value is found in the matrix. There is already a method to test this in IntArrayWorkerTester. Just uncomment the method testGetCount() and the call to it in the main method of IntArrayWorkerTester. 2. Write a getLargest method in the IntArrayWorker class that returns the largest value in the matrix. There is already a method to test this in...

  • Write a function Transpose that transposes a matrix T with M rows and N colums. The...

    Write a function Transpose that transposes a matrix T with M rows and N colums. The transposed matrix, TT, should have N rows and M columns. Example. Given the matrix T. (C++14) Example: 1 2 3 0 -6 7 The transposed matrix TT is 1 0 2 -6 3 7 DEFAULT CODE: Add to code as needed: #include <iostream> #include <string> #include <cmath> using namespace std; void Transpose(int T[100][100], int TT[100][100], int M, int N) { int i; int j;...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • MOdify the program below to do 3x3 matrix mutiplications: #include <iostream> #include <cstdlib> #include <pthread.h> using...

    MOdify the program below to do 3x3 matrix mutiplications: #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; int A[3] [3] = {{1,2},{3,4}}; int B[3] [3] = {{5,6},{7,8}}; int C[3] [3]; struct Position{     int row;     int col; }; void *CalculateElement(void *pos){     Position *p = (Position *)pos;     C[p->row][p->col] = 0;     for(int i = 0; i < 3; i++){         C[p->row][p->col] += A[p->row][i]*B[i][p->col];     }     pthread_exit(NULL); } const int NUM_THREADS = 4; int main() {    ...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • please use eclipse the sample output is incorrect CPS 2231 Chapter 8 Lab 1 Spring 2019...

    please use eclipse the sample output is incorrect CPS 2231 Chapter 8 Lab 1 Spring 2019 1. Write a class, SumOrRows. The main method will do the following methods: a. Call a method, createAndFillArray which: defines a 2 dim array of 3 rows and 4 columns, prompts the user for values and stores the values in the array. b. Calls a method, printArray, which: prints the Array as shown below c. Cails a method, calcSums, which: returns à 1 dimensional...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT