tags:

views:

75

answers:

2

Hello,

I've used an array of strings to populate a DataGridView. How do I go about finding the most frequently occurring number? Or, even better, order them by most frequently occuring?

Thank You.

A: 

Assuming you have one number in each string:

Dim myNumbers As String() = New String() {"9", "9", "8", "8", "8", "8", "7", "7", "6", "5"}

    'NumberCounts will hold the counts of each number
    Dim numberCounts As New System.Collections.Generic.Dictionary(Of String, Integer)

    For Each number As String In myNumbers

        If numberCounts.ContainsKey(number) Then
            'If we've alreade seen this number before, add one to the count
            numberCounts(number) += 1
        Else
            'If it's the first time, add it to the list.
            numberCounts.Add(number, 1)
        End If

    Next number


    ' So now we have the counts of all the numbers, let's sort them 
    Dim sortedCount As New System.Collections.Generic.Dictionary(Of String, Integer)

    'Keep going until there are no more numbers in the numberCount list.
    Do Until numberCounts.Count = 0

        'Find the most occurring number
        Dim maxNumberSoFar As New System.Collections.Generic.KeyValuePair(Of String, Integer)("", 0)

        For Each numberCount As System.Collections.Generic.KeyValuePair(Of String, Integer) In numberCounts
            If numberCount.Value > maxNumberSoFar.Value Then
                'Ha! This number occurres more frequently than the the one we already found
                maxNumberSoFar = numberCount
            End If
        Next numberCount

        'So now we know that we have the most frequently occurring number.

        ' Add it to the results
        sortedCount.Add(maxNumberSoFar.Key, maxNumberSoFar.Value)

        ' Remove it from the numberCount so that we don't count it again
        numberCounts.Remove(maxNumberSoFar.Key)

    Loop

    'Show the results!
    Console.WriteLine("Numbers have been sorted, most frequently to least:")
    For Each displayNumber As System.Collections.Generic.KeyValuePair(Of String, Integer) In sortedCount
        Console.WriteLine("Number " & displayNumber.Key & " occurs " & displayNumber.Value & " times.")
    Next displayNumber

This will also work with any strings, not just numbers. If your numbers are not strings, just use .ToString on them, or change all of the (Of String, Integer) to (Of Long, Integer)

Michael Rodrigues
A: 

If you can use VB 2008, then this may be a little simpler:

Dim myNumbers As String() = New String() {"9", "9", "8", "8", "8", "8", "7", "7", "6", "5"}

Dim counts = From n in myNumbers Group n By n Into Group _
             Select Number = n, Count = Group.Count() _
             Order by Count Descending

For Each c in Counts
    Console.WriteLine("Number: {0}, Count: {1}", c.Number, c.Count)
Next
Chris Dunaway