2011-10-31 8 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

これは宿題ではありません。私は統計的なデータを含む単語文書のためにこの関数が必要です。

答えて

3

は、返信ウィンドウに直接入力するので、ほぼ確実にバグまたは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 
関連する問題