最常见的数字

时间:2010-05-06 23:21:07

标签: vb.net

我使用了一个字符串数组来填充DataGridView。 如何查找最常出现的号码? 或者,更好的是,最频繁地订购它们?

谢谢。

2 个答案:

答案 0 :(得分:1)

假设每个字符串中都有一个数字:

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

这也适用于任何字符串,而不仅仅是数字。如果您的数字不是字符串,只需在它们上使用.ToString,或将所有(Of String,Integer)更改为(Of Long,Integer)

答案 1 :(得分:0)

如果您可以使用VB 2008,那么这可能会更简单一些:

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