Getting hash of a list of strings regardless of order

后端 未结 5 454
谎友^
谎友^ 2020-11-27 11:27

I would like to write a function GetHashCodeOfList() which returns a hash-code of a list of strings regardless of order. Given 2 lists with the same strings sho

5条回答
  •  無奈伤痛
    2020-11-27 12:10

        Dim list1 As ArrayList = New ArrayList()
        list1.Add("0")
        list1.Add("String1")
        list1.Add("String2")
        list1.Add("String3")
        list1.Add("abcdefghijklmnopqrstuvwxyz")
    
        Dim list2 As ArrayList = New ArrayList()
        list2.Add("0")
        list2.Add("String3")
        list2.Add("abcdefghijklmnopqrstuvwxyz")
        list2.Add("String2")
        list2.Add("String1")
        If GetHashCodeOfList(list1) = GetHashCodeOfList(list2) Then
            Stop
        Else
            Stop
        End If
        For x As Integer = list1.Count - 1 To 0 Step -1
            list1.RemoveAt(list1.Count - 1)
            list2.RemoveAt(list2.Count - 1)
            Debug.WriteLine(GetHashCodeOfList(list1).ToString)
            Debug.WriteLine(GetHashCodeOfList(list2).ToString)
            If list1.Count = 2 Then Stop
        Next
    
    
    Private Function GetHashCodeOfList(ByVal aList As ArrayList) As UInt32
        Const mask As UInt16 = 32767, hashPrime As Integer = Integer.MaxValue
        Dim retval As UInt32
        Dim ch() As Char = New Char() {}
        For idx As Integer = 0 To aList.Count - 1
            ch = DirectCast(aList(idx), String).ToCharArray
            For idCH As Integer = 0 To ch.Length - 1
                retval = (retval And mask) + (Convert.ToUInt16(ch(idCH)) And mask)
            Next
        Next
        If retval > 0 Then retval = Convert.ToUInt32(hashPrime \ retval) 'Else ????
        Return retval
    End Function
    

提交回复
热议问题