
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Hamming Distance in a String in JavaScript
Hamming Distance:
The hamming distance between two strings of equal length is the number of positions at which these strings vary.
In other words, it is a measure of the minimum number of changes required to turn one string into another. Hamming Distance is usually measured for strings equal in length.
We are required to write a JavaScript function that takes in two strings, lets say str1 and str2, of the same length. The function should calculate and return the hamming distance between those strings.
Example
Following is the code −
const str1 = 'Hello World'; const str2 = 'Heeyy World'; const findHammingDistance = (str1 = '', str2 = '') => { let distance = 0; if(str1.length === str2.length) { for (let i = 0; i < str1.length; i++) { if (str1[i].toLowerCase() != str2[i].toLowerCase()){ distance++ } } return distance }; return 0; }; console.log(findHammingDistance(str1, str2));
Output
Following is the console output −
3
Advertisements