【问题标题】:Find Consecutive numbers in an Array查找数组中的连续数字
【发布时间】:2011-12-18 11:22:48
【问题描述】:

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

我发现了一些已经提出的问题,但没有一个在 VB.Net 中:

Add to array consecutive numbers

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

这不是家庭作业;我需要这个函数来处理包含统计数据的word文档。

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2016-04-27
      相关资源
      最近更新 更多