我正在尝试将客户的素质通过二进制选择(两个客户)进行比较(例如,一个客户是否使用某种产品),一比二。
经过大量在线搜索之后,看来我需要使用汉明距离(Hamming Distance)或其等效方法:找到两个单词之间进行异或运算的结果的汉明权重。

举一个具体的例子,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

和大量的代码,例如

Hamming weight written only in binary operations?

但仅适用于C,Java,Perl,O,opencl ...除Excel VBA以外的任何语言。

到目前为止,这是我设法做到的。

它有效,但不幸的是,它仅适用于30位或更少的字,并使用了一种粗略的方法:对两个数字X和Y进行XOR,然后转换为代表二进制数的字符串。然后,将数字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


通过计算汉明权重或距离,是否可以帮助使其在VBA for Excel 2010及更低版本(udf或sub)中的96位单词中起作用?

最佳答案

如果您以字符串形式存储质量链(例如,仅由字母“ 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

关于excel-vba - 在VBA Excel中计算汉明重量和/或距离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36045792/

10-10 18:55