Skip to content

Instantly share code, notes, and snippets.

@yury-egorenkov
Created January 15, 2019 16:59
Show Gist options
  • Save yury-egorenkov/e43c49b2549123adcd63ee6aa03cb6a1 to your computer and use it in GitHub Desktop.
Save yury-egorenkov/e43c49b2549123adcd63ee6aa03cb6a1 to your computer and use it in GitHub Desktop.
Just for fun, solution for the https://www.youtube.com/watch?v=10WnvBk9sZc
'use strict';
// 'ABAZDC', 'BACBAD' => 'ABAD'
// 'AGGTAB', 'GXTXAYB' => 'GTAB'
// 'aaaa', 'aa' => 'aa'
// '', '...' => ''
// 'ABBA', 'ABCABA' => 'ABBA'
function longestSubseq (a, b) {
if (typeof a !== 'string') throw Error(`${a} is not a string`)
if (typeof b !== 'string') throw Error(`${b} is not a string`)
let s1 = Array.from(a)
let s2 = Array.from(b)
return s1
.map((_, i) => extractSubseq(s1.slice(i), s2))
.reduce((acc, v) => v.length >= acc.length ? v : acc, '')
}
function extractSubseq (a, b) {
if (!Array.isArray(a)) throw Error(`${a} is not an Array`)
if (!Array.isArray(b)) throw Error(`${b} is not an Array`)
let result = []
let s2 = b.slice()
for (let i = 0; i < a.length; i += 1) {
let index = s2.indexOf(a[i])
if (index !== -1) {
s2 = s2.slice(index + 1, s2.length)
result.push(a[i])
continue
}
}
return result.join('')
}
function main () {
let actual = null
actual = longestSubseq('ABAZDC', 'BACBAD')
if (actual !== 'ABAD') {
throw Error(`Mistmatch. longestSubseq('ABAZDC', 'BACBAD'): ${actual}`)
}
actual = longestSubseq('AGGTAB', 'GXTXAYB')
if (actual !== 'GTAB') {
throw Error(`Mistmatch. longestSubseq('AGGTAB', 'GXTXAYB'): ${actual}`)
}
actual = longestSubseq('aaaa', 'aa')
if (actual !== 'aa') {
throw Error(`Mistmatch. longestSubseq('aaaa', 'aa'): ${actual}`)
}
actual = longestSubseq('aaaa', 'aa')
if (actual !== 'aa') {
throw Error(`Mistmatch. longestSubseq('aaaa', 'aa'): ${actual}`)
}
actual = longestSubseq('', '...')
if (actual !== '') {
throw Error(`Mistmatch. longestSubseq('', '...'): ${actual}`)
}
actual = longestSubseq('ABBA', 'ABCABA')
if (actual !== 'ABBA') {
throw Error(`Mistmatch. longestSubseq('ABBA', 'ABCABA'): ${actual}`)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment