From 7af96ae1cc33e48b7e692e854ec9da1ff4635f23 Mon Sep 17 00:00:00 2001 From: AbhinavXT Date: Sun, 11 Jul 2021 16:30:23 +0530 Subject: [PATCH] Added HammingDistance.js and HammingDistance.test.js in String directory --- String/HammingDistance.js | 32 +++++++++++++++++++++++++++++ String/test/HammingDistance.test.js | 21 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 String/HammingDistance.js create mode 100644 String/test/HammingDistance.test.js diff --git a/String/HammingDistance.js b/String/HammingDistance.js new file mode 100644 index 000000000..d3316f198 --- /dev/null +++ b/String/HammingDistance.js @@ -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 +} diff --git a/String/test/HammingDistance.test.js b/String/test/HammingDistance.test.js new file mode 100644 index 000000000..bc52cafc6 --- /dev/null +++ b/String/test/HammingDistance.test.js @@ -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) +})