Find the most repeating item

  • Thread starter Thread starter Shen
  • Start date Start date
S

Shen

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.

sean
 
Shen said:
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.
 
Thanks a lot Larry. I'll give a try.
Larry Lard said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top