Hamming Distance between two strings in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Hamming Distance

The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.

For example, consider the following strings −

const str1 = 'delhi';
const str2 = 'delph';

The Hamming Distance of these strings is 2 because the fourth and the fifth characters of the strings are different. And obviously in order to calculate the Hamming Distance we need to have two strings of equal lengths.

Therefore, we are required to write a JavaScript function that takes in two strings, let’s say str1 and str2, and returns their hamming distance.

Example

Following is the code −

const str1 = 'delhi';
const str2 = 'delph';
const hammingDistance = (str1 = '', str2 = '') => {
   if (str1.length !== str2.length) {
      return 0;
   }
   let dist = 0;
   for (let i = 0; i < str1.length; i += 1) {
      if (str1[i] !== str2[i]) {
         dist += 1;
      };
   };
   return dist;
};
console.log(hammingDistance(str1, str2));

Output

Following is the output on console −

2
raja
Published on 11-Dec-2020 13:24:38
Advertisements