Created
November 26, 2018 08:32
-
-
Save arthursalvtr/09ca44ac3852c4457709b9a00ab876b9 to your computer and use it in GitHub Desktop.
Longest Common Subsequence in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple Longest Common Subsequence | |
*/ | |
let initial = "ABCDGH"; | |
let compared = "AEDFHR"; | |
let expected = "This is the string"; | |
function assertEquals(expected, actual) | |
{ | |
if (expected === actual) { | |
console.log(`Assert that [${expected}] is [${actual}] is true!`) | |
return | |
} | |
console.error(`Assert that [${expected}] is [${actual}] is false!`) | |
return; | |
} | |
function longestCommonSubsequence(initial, compared) | |
{ | |
let memo = [...Array(initial.length)].map(e => Array(compared.length)); | |
const helper = function (initial, compared, indexOfInitial, indexOfCompared) { | |
if (indexOfInitial === initial.length || indexOfCompared === compared.length) { | |
return ''; | |
} | |
if (memo[indexOfInitial][indexOfCompared] !== undefined) { | |
return memo[indexOfInitial][indexOfCompared]; | |
} | |
if (initial[indexOfInitial] === compared[indexOfCompared]) { | |
return (memo[indexOfInitial][indexOfCompared] = initial[indexOfInitial] + helper(initial, compared, indexOfInitial + 1, indexOfCompared + 1)); | |
} | |
const first = helper(initial, compared, indexOfInitial + 1, indexOfCompared) | |
const second = helper(initial, compared, indexOfInitial, indexOfCompared + 1); | |
if (first.length > second.length) { | |
return memo[indexOfInitial][indexOfCompared] = first; | |
} | |
return memo[indexOfInitial][indexOfCompared] = second; | |
} | |
return helper(initial, compared, 0, 0); | |
} | |
let reg = /([ .,])/g; | |
console.log(initial.split(reg)); | |
let actual = longestCommonSubsequence(initial.split(reg), compared.split(reg)) | |
assertEquals(expected, actual) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment