Skip to content

Instantly share code, notes, and snippets.

@shedali
Created February 20, 2014 09:58
Show Gist options
  • Save shedali/9110319 to your computer and use it in GitHub Desktop.
Save shedali/9110319 to your computer and use it in GitHub Desktop.
find longest common non-contiguous subsequence
var fs = require("fs");
var a, b, split,
longest = '',
sequence = '',
output = '',
matched = 0,
matchpos = 0;
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function(line) {
sequence = '';
if (!line) {
return;
}
var split = line.split(';');
a = reverse(split[0]);
b = reverse(split[1]);
console.log(getseq(a, b)); //output answer
});
function getseq(one, two) {
if (one === '' || two === '') {
return reverse(sequence);
}
if (one.charAt(0) === two.charAt(0)) { //matching character, save
sequence += one.charAt(0);
return getseq(one.substr(1), two.substr(1));
} else {
var nexta = one.charAt(0);
var nextb = two.charAt(0);
var matchFound = false;
if (!contains(one, nextb)) {
return getseq(one, two.substr(two.indexOf(nextb) + 1));
} else {
matchFound = true;
}
if (!contains(two, nexta)) {
return getseq(one.substr(one.indexOf(nexta) + 1), two);
} else {
matchFound = true;
}
if (!matchFound) { //neither have char, eat both
return getseq(one.substr(1), two.substr(1));
}
if (two.indexOf(nexta) < one.indexOf(nextb)) {
return getseq(one, two.substr(1));
} else {
return getseq(one.substr(1), two);
}
}
}
function contains(owner, char) {
return owner.indexOf(char) !== -1;
}
function reverse(str) {
return str.split("").reverse().join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment