I have this coding challenge that I can't stop thinking about and I couldn't solve. You are given 2 strings that represent 2 DNA sequences, for example: dna1 = "ATGGTTAT" dna2 = "AGTGTTAT" The sequences sizes are the same (they can have from 7 to 8 characters) and if they have any matching substrings, you should compare them and return the first largest matching substring's position.
Example: dna1 = "AAGGTGAT" dna2 = "AATGTGAT" The output should be 3.
I tried using for loops to iterate and compare both sequences and return the position, but i can't find a way to separate the matching substrings, compare them and return the position. Is there any easy way for doing that? Or is there a better language to do this?(I used javascrip)
CodePudding user response:
Since you are only comparing characters in the same position in both strings, you only need one loop:
function mm(a, b) {
let longest = 0;
let longestPos = -1;
let pos = 0;
let len = 0;
while (pos < a.length) {
if (a[pos] == b[pos]) {
len ;
if (len > longest) {
longest = len;
longestPos = pos - len 1;
}
} else {
len = 0;
}
pos ;
}
return longestPos;
}
console.log(mm('AAGGTGAT', 'AATGTGAT'))