在数组中查找连续的数字 [英] 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.
我发现了一些已经问过的问题,但没有一个在 VB.Net 中:
I found some of the already asked questions but none of them is in VB.Net:
如果数字数组看起来像 {11,12,67,68,69,70,92,97}
那么返回的字符串应该是 11,12, 67通过 70、92 和 97
.
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
.
这不是作业;对于包含统计数据的 word 文档,我需要这个函数.
This is not homework; I need this function for a word document containing statistical data.
推荐答案
直接进入回复窗口,所以几乎可以肯定有一个或三个错误:
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
这篇关于在数组中查找连续的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!