在VBA Excel中计算汉明重量和/或距离

3
我想比较两个客户端,通过二元选择来定义它们的质量(例如客户端是否使用产品)。经过网上搜索,看起来我需要使用汉明距离或其等效方法:找到两个字之间XOR操作结果的汉明权重。
以具体例子为例,“1001”和“1011”的汉明距离:
计算1001 XOR 1011 = 0010的数量
0010的汉明权重= 1(在0010中设置为1的位数)
我需要对长达96位的单词这样做。
我在网上找到了一些信息。

http://people.revoledu.com/kardi/tutorial/Similarity/HammingDistance.html

http://trustedsignal.blogspot.ca/2015/06/xord-play-normalized-hamming-distance.html

我有很多编程代码片段,例如:

仅使用二进制操作编写的汉明重量算法?

但只适用于C、Java、Perl、O、opencl等语言,不适用于Excel VBA。

到目前为止,这是我能够整理出来的:

它可以工作,但遗憾的是只适用于30位或更少位的单词,并且使用了一种比较粗糙的方法:对两个数字X和Y进行异或运算,然后将其转换为表示二进制数的字符串。然后在去除1后计算字符串的长度。我想可能还有更优雅和高效的方法。

Public Function HamDist(x As Long, y As Long, NbBit As Integer)

Dim i As Long, BinStrg As String, bxor As Long 

bxor = x Xor y 

BinStrg = "" 

For i = NbBit To 0 Step -1 ‘going from left to right 
         If bxor And (2 ^ i) Then
            BinStrg = BinStrg + "1" ‘add a 1 to the string 
         Else
            BinStrg = BinStrg + "0"
         End If
      Next

 HamDist = Len(BinStrg) - Len(Replace(BinStrg, "1", "")) ' replace the 1 by nothing and count  the length of the resulting string 
End Function

你能帮忙让它在Excel 2010及以下版本的VBA中适用于96位单词(UDF或子程序),无论是通过计算海明重量还是距离?


1
你的xy不能是Long。对于96位,您必须使用字符串作为输入而不是IntegerLongLongLongDouble,因为它们都只存储了64位或更少的位数。这很不方便,需要您编写大型数字算术函数像这里 - Alexis Olson
1个回答

2
如果您将品质链以字符串形式存储(例如,仅由字母'T'和'F'组成的字符串),那么可以很容易地使用循环来完成此操作。
Function hammingDistance(qualities1 As String, qualities2 As String) As Integer

    If Len(qualities1) <> Len(qualities2) Then
        hammingDistance = -1
        Exit Function
    End If

    Dim i, result As Integer
    result = 0

    For i = 1 To Len(qualities1)
        If Mid(qualities1, i, 1) <> Mid(qualities2, i, 1) Then result = result + 1
    Next

    hammingDistance = result

End Function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接