2011-10-31 35 views
2

我需要在數組中找到連續的數字,並返回一個字符串,它告訴範圍和數字不構成範圍。在數組中找到連續的數字

,我發現了一些已經問過的問題,但他們都不是在VB.Net:

Add to array consecutive numbers

如果數字的陣列看起來像{11,12,67,68,69,70,92,97}然後返回的字符串應該是形式爲11,12, 67 through 70, 92 and 97

這不是家庭作業;我需要這個函數來處理包含統計數據的word文檔。

回答

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