I am kinda new in VB.net; pretty much what I have been looking for is a way to calculate the similarity of a byte array. I have been able to determine whether they are equal or not, but I haven't figured out how to calculate how similar they are in percentage. Any idea is appreciated. Thanks! Leo.
The following function takes two Byte arrays as its arguments. If the arrays are not the same length, it throws an exception. Otherwise, it returns the fraction of the elements in one array that are equal to the element at the same position in the other array.
Function PercentAlike(array1() As Byte, array2() As Byte) As Double
If array1.Length <> array2.Length Then Throw New ArgumentException("Arrays must have the same length")
Dim same As Integer
For i As Integer = 0 To array1.Length - 1
If array1(i) = array2(i) Then same += 1
Next
Return same / array1.Length
End Function
[Added in response to the comment that the arrays may not be the same length] If you need to calculate a percentage even if the arrays are of different lengths, you can use the following function. It returns the number of elements in one array that are equal to the element at the same position in the other array (ignoring the extra elements in the longer array) as a fraction of the number of elements in the longer array.
Function PercentAlike(array1() As Byte, array2() As Byte) As Double
Dim same As Integer
For i As Integer = 0 To Math.Min(array1.Length, array2.Length) - 1
If array1(i) = array2(i) Then same += 1
Next
Return same / Math.Max(array1.Length, array2.Length)
End Function