Paulos3000 Paulos3000 - 4 months ago 20
Javascript Question

'Hamming' javascript test (Exercism) - matching letters between two strings

Doing this 'Hamming' test on Exercism, and I'm struggling to see what's wrong with my function - would appreciate if someone could shed some light:

Spec



it('small hamming distance in longer strand', function () {
expect(hamming.compute('GGACG', 'GGTCG')).toEqual(1);
});


For every character that doesn't match between the two strings sequentially, I want to add 1. So in this case, G===G (0), G===G (0), A!==T (1), C===C (1), G===G (1).

So, as indicated in the spec, I would expect 1 to be returned.

However my function below returns 5.

My Function



this.compute = function(dna1, dna2) {

var mismatches = 0;

for (var i = 0; i <= dna1.length; i++) {
if (dna1[i] === dna2[i]) {
mismatches ++;
}
}

return mismatches;

}


Can anyone explain where I'm going wrong?

Thanks in advance!

Answer

If you expect difference, you function should be like :

this.compute = function(dna1, dna2) { 

  var mismatches = 0;

  for (var i = 0; i <= dna1.length; i++) {
    if (dna1[i] != dna2[i]) {//if character not equals
      mismatches ++;
    }
  }

  return mismatches;

}