Skip to content

Commit 6f3ea82

Browse files
algorithm: Added Hamming Distance (#83)
* Added hamming distance algorithm implementation🐹 * Fixed some style issues * Update DIRECTORY.md Co-authored-by: autoprettier <actions@github.com>
1 parent ca4cf6d commit 6f3ea82

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
* [Fibonacci](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/fibonacci.ts)
2121
* [Find Min](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/find_min.ts)
2222
* [Greatest Common Factor](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/greatest_common_factor.ts)
23+
* [Hamming Distance](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/hamming_distance.ts)
2324
* [Is Divisible](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_divisible.ts)
2425
* [Is Even](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_even.ts)
2526
* [Is Leap Year](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/is_leap_year.ts)

maths/hamming_distance.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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++) if (str1[i] !== str2[i]) dist++
21+
22+
return dist
23+
}
24+
25+
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)