In: Computer Science
Please give Java Code ASAP
Matrix Multiplication Due Friday 30th October 2020 by 23:55.
For this exercise, you are to find the optimal order for multiplying a sequence of matrices. Note: you do not actually have to perform any matrix multiplications. As usual, your program will prompt for the name of an input file and the read and process the data contained in this file.
The file contains the following data. N, the number of matrices to be multiplied together N pairs of integers which are the row and column dimensions of each matrix. E.g.
The following input
3 3 4 4 2 2 5
Defines a problem in which we are to multiply three matrices, say M[0], M[1] and M[2], where:
M[0] has 3 rows and 4 columns; M[1] has 4 rows and 2 columns; M[2] has 2 rows and 5 columns.
Output for the program is the value of best(0,N), the minimum number of multiplications required to compute the matrix R = M[0]xM[1]x…xM[N‐1].
You may leave your solution as a memoized, recursive formulation if you have problems formulating the looped iterative scheme.
As usual, do not use classes or STL. Submit ex10.ext via moodle as usual where ext is one of c, cpp, java or py.
import java.io.*;
import java.util.*;
public class Main
{
// function to calculate minimum multiplication count
public static int minMultiplication(int arr[], int start, int end)
{
int res=Integer.MAX_VALUE;// stores min value of multiplication count required
if(start!=end)
{
for(int i=start;i<end;i++)
{
int temp=minMultiplication(arr,start,i)+minMultiplication(arr,i+1,end)+arr[start-1]*arr[i]*arr[end];
if(temp<res)
res=temp;
}
}
else
res=0;
return res;
}
// driver code
public static void main(String[] args) throws Exception{
Scanner s=new Scanner(System.in);
System.out.print("Enter input file name: ");
String file=s.nextLine();
BufferedReader br=new BufferedReader(new FileReader(file));
String ll=br.readLine();
int n=Integer.parseInt(ll.trim());// total number of matrices
int m[]=new int[n+1];
int k=0,count=1;
while((ll=br.readLine())!=null){// loop till line in file is present
String mm[]=ll.split("\\s+");// split string on space
if(count==1){// for first matrix
m[k++]=Integer.parseInt(mm[0]);
m[k++]=Integer.parseInt(mm[1]);
}
else{
m[k++]=Integer.parseInt(mm[1]);
}
count++;
}
System.out.println("Minimum number of multiplication required: "+minMultiplication(m,1,m.length-1));
}
}