Skip to content
Open
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
25 changes: 25 additions & 0 deletions Maths/HammingDistance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @function hammingDistance
* @description Hamming distance between two integers is the number of
* positions at which the corresponding bits are different.
* @param {number} a - First non-negative integer
* @param {number} b - Second non-negative integer
* @returns {number} - The Hamming distance between a and b
* @see https://en.wikipedia.org/wiki/Hamming_distance
* @example hammingDistance(1, 4) => 2
* @example hammingDistance(3, 1) => 1
*/
const hammingDistance = (a, b) => {
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) {
throw new TypeError('Inputs must be non-negative integers')
}
let xor = a ^ b
let distance = 0
while (xor > 0) {
distance += xor & 1
xor >>= 1
}
return distance
}

export { hammingDistance }
36 changes: 36 additions & 0 deletions Maths/test/HammingDistance.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { hammingDistance } from '../HammingDistance.js'

describe('hammingDistance', () => {
test('hammingDistance(1, 4) returns 2', () => {
expect(hammingDistance(1, 4)).toBe(2)
})

test('hammingDistance(3, 1) returns 1', () => {
expect(hammingDistance(3, 1)).toBe(1)
})

test('hammingDistance(0, 0) returns 0', () => {
expect(hammingDistance(0, 0)).toBe(0)
})

test('hammingDistance(7, 0) returns 3', () => {
expect(hammingDistance(7, 0)).toBe(3)
})

// TO:
test('hammingDistance(10, 14) returns 1', () => {
expect(hammingDistance(10, 14)).toBe(1)
})

test('hammingDistance(same numbers) returns 0', () => {
expect(hammingDistance(5, 5)).toBe(0)
})

test('throws TypeError for negative input', () => {
expect(() => hammingDistance(-1, 4)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => hammingDistance(1.5, 4)).toThrow(TypeError)
})
})
Loading