Skip to content

Instantly share code, notes, and snippets.

@ungarson
Last active May 12, 2019 09:37
Show Gist options
  • Save ungarson/c905c73c153e9901abc7c6c674384829 to your computer and use it in GitHub Desktop.
Save ungarson/c905c73c153e9901abc7c6c674384829 to your computer and use it in GitHub Desktop.
Finding a Longest Common Subsequence of two strings in javascript
function forwardTrace(lcsMatrix, set1, set2) {
for (let rowIndex = 1; rowIndex <= set2.length; rowIndex += 1) {
for (let columnIndex = 1; columnIndex <= set1.length; columnIndex += 1) {
if (set1[columnIndex - 1] === set2[rowIndex - 1]) {
lcsMatrix[rowIndex][columnIndex] = lcsMatrix[rowIndex - 1][columnIndex - 1] + 1;
} else {
lcsMatrix[rowIndex][columnIndex] = Math.max(
lcsMatrix[rowIndex - 1][columnIndex],
lcsMatrix[rowIndex][columnIndex - 1],
);
}
}
}
}
function backTrace(lcsMatrix, set1, set2) {
const longestSequence = [];
let columnIndex = set1.length;
let rowIndex = set2.length;
while (columnIndex > 0 || rowIndex > 0) {
if (set1[columnIndex - 1] === set2[rowIndex - 1]) {
// Move by diagonal left-top.
longestSequence.unshift(set1[columnIndex - 1]);
columnIndex -= 1;
rowIndex -= 1;
} else if (lcsMatrix[rowIndex][columnIndex] === lcsMatrix[rowIndex][columnIndex - 1]) {
// Move left.
columnIndex -= 1;
} else {
// Move up.
rowIndex -= 1;
}
}
return longestSequence;
}
function LCS(set1, set2) {
string1 = set1.trim();
string2 = set2.trim();
const len1 = string1.length;
const len2 = string2.length;
// create two dimensional array (len1+1)*(len2+1)
let arr = Array(len2 + 1).fill(null).map(() => Array(len1 + 1).fill(null));
// filling first horizontal and verical line with zeroes
arr[0].fill(0);
for (let i = 0; i <= string1.length; i++) {
arr[i][0] = 0;
}
forwardTrace(arr, string1, string2);
const string = backTrace(arr, string1, string2);
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment