开发者

Getting the index of the largest integer in an array

开发者 https://www.devze.com 2023-03-07 23:01 出处:网络
I have an array of integers and I need to know the index of the largest number (not the actual value, just the index of whichever is highest).

I have an array of integers and I need to know the index of the largest number (not the actual value, just the index of whichever is highest).

However, if one or more indexes "tie" for the highest value, I need to have all of the indexes that share tha开发者_如何学Ct high value.

I assume this function would need to return an array (since it could be one or more indexes), but I am not totally sure how to go about getting the more efficient solution.


If this is going to be a common thing you could write your own Extension. You should add some additional sanity/null checking but this will get you started:

Module Extensions
    <System.Runtime.CompilerServices.Extension()> Function FindAllIndexes(Of T)(ByVal array() As T, ByVal match As Predicate(Of T)) As Integer()

        ''//Our return object
        Dim Ret As New List(Of Integer)

        ''//Current array index
        Dim I As Integer = -1

        ''//Infinite loop, break out when we no more matches are found
        Do While True
            ''//Loop for a match based on the last index found, add 1 so we dont keep returning the same value
            I = System.Array.FindIndex(array, I + 1, match)

            ''//If we found something
            If I >= 0 Then
                ''//Append to return object
                Ret.Add(I)
            Else
                ''//Otherwise break out of loop
                Exit Do
            End If
        Loop

        ''//Return our array
        Return Ret.ToArray()
    End Function
End Module

Then to call it:

    Dim ints As Integer() = New Integer() {1, 2, 8, 6, 8, 1, 4}
    Dim S = ints.FindAllIndexes(Function(c) c = ints.Max())
    ''//S now holds 2 and 4


If you are using .NET 3.5, you can use the Max() Extension function to easily find the highest value, and use Where to locate the matching records in your source array.


IList has an IndexOf member, which helps. This code is completely untested, and probably has at least one off-by-one error.

   Public Function GetPostionsOfMaxValue(ByVal input() As Integer) As Integer()

            Dim ints = New List(Of Integer)(input)
            Dim maxval = ints.Max

            Dim indexes As New List(Of Integer)
            Dim searchStart As Integer = 0

            Do Until searchStart >= ints.Count
                Dim index = ints.IndexOf(maxval, searchStart)
                If index = -1 Then Exit Do
                indexes.Add(index)
                searchStart = index + 1
            Loop

            Return indexes.ToArray

        End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消