0% found this document useful (0 votes)
41 views2 pages

Experiment - 8: Aim: WAP To Implement MCM (Matrix Chain Multplication)

This Java program implements the Matrix Chain Multiplication (MCM) algorithm to find the most efficient way to multiply a sequence of matrices. It initializes the matrix dimensions, calculates the minimum cost of multiplying the matrices using dynamic programming, and returns the result. The program takes in 5 matrices of varying dimensions, stores their dimensions and minimum multiplication costs in arrays, and uses nested for loops to iterate through the arrays to find the lowest overall cost according to the MCM algorithm in O(n^3) time.

Uploaded by

shubham ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views2 pages

Experiment - 8: Aim: WAP To Implement MCM (Matrix Chain Multplication)

This Java program implements the Matrix Chain Multiplication (MCM) algorithm to find the most efficient way to multiply a sequence of matrices. It initializes the matrix dimensions, calculates the minimum cost of multiplying the matrices using dynamic programming, and returns the result. The program takes in 5 matrices of varying dimensions, stores their dimensions and minimum multiplication costs in arrays, and uses nested for loops to iterate through the arrays to find the lowest overall cost according to the MCM algorithm in O(n^3) time.

Uploaded by

shubham ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

EXPERIMENT - 8

Aim: WAP to implement MCM(Matrix Chain Multplication)

import java.io.*;
import java.util.*;
import java.lang.StringBuffer;

public class MaCM {


public int N[][];
public int d[];
public int SIZE = 5;

public static void main(String[] args) throws Exception {


MaCM mcm = new MaCM();

mcm.init();

int result = mcm.minMCM();

System.out.println("result = " + result);


}

public void init() {


N = new int[SIZE][SIZE];
d = new int[SIZE + 1];

for (int i = 0; i < SIZE; i++) {


for (int j = 0; j < SIZE; j++) {
if (i == j)
N[i][j] = 0;
else
N[i][j] = 999;
}
}

d[0] = 2;
d[1] = 4;
d[2] = 2;
d[3] = 3;
d[4] = 1;
d[5] = 4;
}

public int minMCM() {

for (int i = 1; i <= SIZE; i++) {


for (int j = 0; j <= SIZE - i; j++) {
for (int k = j; k < j + i - 1; k++) {
if (N[j][j + i - 1] > N[j][k] + N[k + 1][j + i - 1]
+ d[j]
* d[k + 1] * d[i + j]) {
N[j][j + i - 1] = N[j][k] + N[k + 1][j + i -
1] + d[j]
* d[k + 1] * d[i + j];
}
}
}
}

System.out.println("N = ");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print(N[i][j] + "\t");
}
System.out.println();
}

System.out.println();
return N[0][SIZE - 1];
}
}

OUTPUT:

You might also like