Skip to content

Commit 49c5cc7

Browse files
committed
matrixChainOrder dp
1 parent 39243c9 commit 49c5cc7

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title></title>
6+
</head>
7+
<body>
8+
<script src="10-MatrixChainMultiplicationDP.js"></script>
9+
</body>
10+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
function matrixChainOrder(p, n) {
2+
3+
var i, j, k, l, q,
4+
m = [], s=[];
5+
6+
for (i = 1; i <= n; i++){
7+
m[i] = [];
8+
m[i][i] = 0;
9+
10+
}
11+
12+
for (i = 0; i <= n; i++){ //to help printing the optimal solution
13+
s[i] = []; //auxiliary
14+
for (j=0; j<=n; j++){
15+
s[i][j] = 0;
16+
}
17+
}
18+
19+
for (l=2; l<n; l++) {
20+
for (i=1; i<=n-l+1; i++) {
21+
j = i+l-1;
22+
m[i][j] = Number.MAX_SAFE_INTEGER;
23+
for (k=i; k<=j-1; k++) {
24+
// q = cost/scalar multiplications
25+
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
26+
if (q < m[i][j]){
27+
m[i][j] = q;
28+
s[i][j]=k; // s[i,j] = Second auxiliary table that stores k
29+
}
30+
}
31+
}
32+
}
33+
34+
console.log(m);
35+
console.log(s);
36+
37+
printOptimalParenthesis(s, 1, n-1);
38+
39+
return m[1][n-1];
40+
}
41+
42+
function printOptimalParenthesis(s, i, j){
43+
if(i == j) {
44+
console.log("A[" + i + "]");
45+
} else {
46+
console.log("(");
47+
printOptimalParenthesis(s, i, s[i][j]);
48+
printOptimalParenthesis(s, s[i][j] + 1, j);
49+
console.log(")");
50+
}
51+
}
52+
53+
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
54+
var p = [10, 100, 5, 50, 1],
55+
n = p.length;
56+
console.log(matrixChainOrder(p, n));

0 commit comments

Comments
 (0)