Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions String/HammingDistance.js
Original file line number Diff line number Diff line change
@@ -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 changes: 21 additions & 0 deletions String/test/HammingDistance.test.js
Original file line number Diff line number Diff line change
@@ -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)
})