Find Consecutive numbers in an Array

我的未来我决定 提交于 2021-01-27 17:46:34

问题


I need to find consecutive numbers in an array and return a string which tells the range and numbers that don't form a range.

I found some of the already asked questions but none of them is in VB.Net:

Add to array consecutive numbers

If the array of numbers looks like {11,12,67,68,69,70,92,97} then returned string should be of the form 11,12, 67 through 70, 92 and 97.

This is not homework; I need this function for a word document containing statistical data.


回答1:


Entered directly into the reply window, so there's almost certainly a bug or three:

Public Class Range

    Public Shared Function PrintRanges(ByVal numbers() As Integer) As String
        Dim buffer As New List(Of Range)()
        Dim CurrentRange As Range = Nothing

        For Each i As Integer in numbers ' you may want to add a .OrderBy() here
            If CurrentRange IsNot Nothing AndAlso i - 1 = CurrentRange.EndValue Then
                 CurrentRange.Increase()
            Else
                CurrentRange = New Range(i)
                buffer.Add(CurrentRange)
            End If
        Next i

        'Got a little lazy for this line - it still does a ", " rather than " and " for the final delimiter. Simple code to fix it, just tedious.
        Return String.Join(", ", buffer.Select(Function(r) r.ToString()).ToArray())
    End Function

    Private Sub New(ByVal InitialValue As Integer)
        EndValue = IntialValue
        Length = 1
    End Sub

    'For completeness, these two properties should be made read only outside the class, but the private constructor makes that largely moot
    Public Property EndValue As Integer
    Public Property Length As Integer

    Public Sub Increase()
         Length += 1
         EndValue += 1
    End Sub

    Public Overrides Function ToString() As String
        If Length == 1 Then Return EndValue.ToString()
        If Length == 2 Then Return (EndValue -1).ToString() & "," & LastValue.ToString()
        Return (EndValue - Length).ToString() & " through " & EndValue.ToString()
    End Function

End Class


来源:https://stackoverflow.com/questions/7949600/find-consecutive-numbers-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!