HammingDistance [汉明距离]
# 介绍
在信息论中,两个等长字符串之间的汉明距离(英语:Hamming distance)是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。
汉明重量是字符串相对于同样长度的零字符串的汉明距离,也就是说,它是字符串中非零的元素个数:对于二进制字符串(binary data strings)来说,就是 1 的个数,所以 11101 的汉明重量是 4。
# 实现
# JavaScript
/**
* 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}
*/
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;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 参考
编辑 (opens new window)
上次更新: 2022/10/20, 20:45:42