I have an array filled with counts of numbers. Example:
ar(1) contains the number of occurrances of the number 1
ar(2) contains the number of occurrances of the number 2
etc...
I need to find the 10 numbers with the highest occurrances.
I must be overlooking something but i've been beating my head against the
wall for a couple of hours now playing with arrays. Someone point me in the
right direction?
This seems like huge overkill, but if I understood your problem it's
the first thing that came to mind. Basically, I transformed the
original array into a list of KeyValue pairs (to maintain the index in
the original array), sorted the List with a custom comparer, and
turned it back into an array. The following is a Console project, just
copy and paste it in and you'll see what I mean:
////////////////////////
Module Module1
Sub Main()
'// Demo array
Dim array As Integer() = {73, 5, 13, 41, 2, 4, 53, 42, 14, 15,
16, 67}
'// Our List
Dim list As New List(Of KeyValuePair(Of Integer, Integer))
'// Move the array to the list
For i As Integer = 0 To array.Length - 1
list.Add(New KeyValuePair(Of Integer, Integer)(i,
array(i)))
Next
'// Sort the List by Values
list.Sort(New MyComparer())
'// Move the List back to an Array
Dim newArray As KeyValuePair(Of Integer, Integer)() =
list.ToArray()
'// Print the top 10 results
For i As Integer = 0 To 9
Console.WriteLine("{0} with {1} occurrances",
newArray(i).Key, newArray(i).Value)
Next
Console.Read()
End Sub
End Module
Public Class MyComparer
Implements IComparer(Of KeyValuePair(Of Integer, Integer))
Public Function Compare(ByVal x As
System.Collections.Generic.KeyValuePair(Of Integer, Integer), ByVal y
As System.Collections.Generic.KeyValuePair(Of Integer, Integer)) As
Integer Implements System.Collections.Generic.IComparer(Of
System.Collections.Generic.KeyValuePair(Of Integer, Integer)).Compare
If x.Value = y.Value Then
Return 0
ElseIf x.Value < y.Value Then
Return 1
Else
Return -1
End If
End Function
End Class
////////////////////////
Thanks,
Seth Rowe