user1021333
user1021333

Reputation: 21

Find Consecutive numbers in an Array

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.

Upvotes: 2

Views: 1686

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416121

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

Upvotes: 3

Related Questions