Skip to content

Commit d0e95a5

Browse files
committed
Added hamming distance algorithm implementation🐹
1 parent ca4cf6d commit d0e95a5

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

maths/hamming_distance.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function HammingDistance
3+
* @description Returns the Hamming distance between two strings of equal length
4+
* @summary The Hamming distance between two strings of equal length is the
5+
* number of positions at which the corresponding symbols are different. In other words,
6+
* it measures the minimum number of substitutions required, to change one string to the other
7+
* It is one of the several sring metrics, used fror measuring the edit distance between two sequences
8+
* and is named after the American mathematician Richard Hamming
9+
* @param str1 One of the strings to compare to the other
10+
* @param str2 One of the strings to compare to the other
11+
* @returns {number}
12+
* @see [Wikipedia](https://en.wikipedia.org/wiki/Hamming_distance)
13+
* @example HammingDistance('happy', 'homie')
14+
*/
15+
const HammingDistance = (str1: string, str2: string) => {
16+
if (str1.length !== str2.length) throw new Error('Strings must of the same length.')
17+
18+
let dist = 0
19+
20+
for (let i = 0; i < str1.length; i += 1) {
21+
if (str1[i] !== str2[i]) dist += 1
22+
}
23+
24+
return dist
25+
}
26+
27+
export { HammingDistance }

maths/test/hamming_distance.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { HammingDistance } from "../hamming_distance"
2+
3+
test.each([['happy', 'homie', 4], ['hole', 'home', 1], ['cathrine', 'caroline', 3], ['happiness', 'dizziness', 4]])('Hamming Distance', (str1, str2, result) => {
4+
expect(HammingDistance(str1, str2)).toBe(result)
5+
})

0 commit comments

Comments
 (0)