mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
chore: Merge pull request #635 from AbhinavXT/HammingDistance
Added HammingDistance.js and HammingDistance.test.js in String directory
This commit is contained in:
32
String/HammingDistance.js
Normal file
32
String/HammingDistance.js
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
/**
|
||||||
|
* Hamming Distance: https://en.wikipedia.org/wiki/Hamming_distance
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* Hamming distance is a metric for comparing two binary data strings.
|
||||||
|
*
|
||||||
|
* While comparing two binary strings of equal length, Hamming distance
|
||||||
|
* is the number of bit positions in which the two bits are different.
|
||||||
|
* The Hamming distance between two strings, a and b is denoted as d(a,b)
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} a
|
||||||
|
* @param {string} b
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const hammingDistance = (a, b) => {
|
||||||
|
if (a.length !== b.length) {
|
||||||
|
throw new Error('Strings must be of the same length')
|
||||||
|
}
|
||||||
|
|
||||||
|
let distance = 0
|
||||||
|
|
||||||
|
for (let i = 0; i < a.length; i += 1) {
|
||||||
|
if (a[i] !== b[i]) {
|
||||||
|
distance += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return distance
|
||||||
|
}
|
21
String/test/HammingDistance.test.js
Normal file
21
String/test/HammingDistance.test.js
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import { hammingDistance } from '../HammingDistance'
|
||||||
|
|
||||||
|
test('should throw an error when trying to compare the strings of different length', () => {
|
||||||
|
const compareStringsOfDifferentLength = () => {
|
||||||
|
hammingDistance('abc', 'abcd')
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(compareStringsOfDifferentLength).toThrowError()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should calculate difference between two strings', () => {
|
||||||
|
expect(hammingDistance('a', 'a')).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should calculate difference between two strings', () => {
|
||||||
|
expect(hammingDistance('abc', 'add')).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('should calculate difference between two strings', () => {
|
||||||
|
expect(hammingDistance('1011101', '1001001')).toBe(2)
|
||||||
|
})
|
Reference in New Issue
Block a user