在数组中查找连续数字

时间:2011-10-31 02:59:30

标签: vb.net visual-studio visual-studio-2008

我需要在数组中找到连续的数字并返回一个字符串,该字符串告诉范围和不形成范围的数字。

我找到了一些已经问过的问题,但是没有一个问题出现在VB.Net中:

  

Add to array consecutive numbers

如果数字数组看起来像{11,12,67,68,69,70,92,97},则返回的字符串应为11,12, 67 through 70, 92 and 97形式。

这不是作业;我需要这个函数用于包含统计数据的word文档。

1 个答案:

答案 0 :(得分:3)

直接进入回复窗口,几乎可以肯定是一个或三个错误:

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