forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-LongestCommonSubsequenceDP.js
105 lines (83 loc) · 2.25 KB
/
08-LongestCommonSubsequenceDP.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
function lcs(wordX, wordY) {
var m = wordX.length,
n = wordY.length,
l = [],
i, j, a, b;
for (i = 0; i <= m; ++i) {
l[i] = [];
for (j = 0; j <= n; ++j) {
l[i][j] = 0;
}
}
for (i=0; i<=m; i++) {
for (j=0; j<=n; j++) {
if (i == 0 || j == 0){
l[i][j] = 0;
} else if (wordX[i-1] == wordY[j-1]) {
l[i][j] = l[i-1][j-1] + 1;
} else {
a = l[i-1][j];
b = l[i][j-1];
l[i][j] = (a > b) ? a : b; //max(a,b)
}
}
console.log(l[i].join());
}
return l[m][n];
}
//complete algorithm that prints the LCS as well
function lcs2(wordX, wordY) {
var m = wordX.length,
n = wordY.length,
l = [],
solution = [],
i, j, a, b;
for (i = 0; i <= m; ++i) {
l[i] = [];
solution[i] = [];
for (j = 0; j <= n; ++j) {
l[i][j] = 0;
solution[i][j] = '0';
}
}
for (i=0; i<=m; i++) {
for (j=0; j<=n; j++) {
if (i == 0 || j == 0){
l[i][j] = 0;
} else if (wordX[i-1] == wordY[j-1]) {
l[i][j] = l[i-1][j-1] + 1;
solution[i][j] = 'diagonal';
} else {
a = l[i-1][j];
b = l[i][j-1];
l[i][j] = (a > b) ? a : b; //max(a,b)
solution[i][j] = (l[i][j] == l[i - 1][j]) ? 'top' : 'left';
}
}
console.log(l[i].join());
console.log(solution[i].join());
}
printSolution(solution, l, wordX, wordY, m, n);
return l[m][n];
}
function printSolution(solution, l, wordX, wordY, m, n){
var a = m, b = n, i, j,
x = solution[a][b],
answer = '';
while (x !== '0') {
if (solution[a][b] === 'diagonal') {
answer = wordX[a - 1] + answer;
a--;
b--;
} else if (solution[a][b] === 'left') {
b--;
} else if (solution[a][b] === 'top') {
a--;
}
x = solution[a][b];
}
console.log('lcs: '+ answer);
}
var wordX = 'acbaed',
wordY = 'abcadf';
console.log(lcs2(wordX, wordY));