Shen wrote:
Hi,
I have an array/arraylist of string items. What I want is to find out
which item repeats itself most often. Any simple example for that? Thanks
in advance.
Use an implementation of IDictionary (I use a HashTable here) to enable
the use of strings as keys:
Public Function ArrayMode(ByVal Strings() As String) As String
Dim ht As Hashtable = New Hashtable(Strings.Length \ 2)
Dim s As String, occurrences As Integer
Dim ModalString As String, ModalOccurrences As Integer = 0
For Each s In Strings
If ht.Contains(s) Then
occurrences = CInt(ht.Item(s))
occurrences += 1
ht.Item(s) = occurrences
Else
occurrences = 1
ht.Add(s, occurrences)
End If
If occurrences > ModalOccurrences Then
ModalOccurrences = occurrences
ModalString = s
End If
Next
Return ModalString
End Function
If you want to accept an ArrayList, change the first two lines to
Public Function ArrayMode(ByVal Strings As ArrayList) As String
Dim ht As Hashtable = New Hashtable(Strings.Count \ 2)
No guarantees that this is the best way :) For example, you could have
the routine notice that if a given string ever gets more than n/2
votes, it will definitely be the winner, so there is no point checking
the rest.
--
Larry Lard
Replies to group please