给定区间[a1,a2]和[b1,b2],若a2≥b1,则认为这两个区间是有重叠的,可进行合并。如区间[1,3]和[2,6]可合并为[1,6];区间[1,6],[2,5]可合并为[1,6];区间[1,4]和[4,5]可合并为[1,5]。
编写一个“合并重叠区间”的VB程序,功能如下:在文本框Text1中按各区间起始值升序依次输入各区间的起始值和终止值(数据都用逗号分隔并以逗号结尾),单击“确定”按钮后,在Text2中显示合并后的各个区间。例如,在文本框Text1中输入“1,2,3,5,4,6,9,12,10,11,”,表示区间[1,2],[3,5],[4,6],[9,12],[10,11],合并后的区间分别为[1,2],[3,6],[9,12]。程序运行界面如图所示,实现上述功能的VB代码如下:
Const n=100
Private Sub Cmd1_Click()
Dim i As Integer, k As Integer, L As Integer, R As Integer
Dim s As String, c As String, t As String, result As String
Dim a(1 To n) As Integer
s= ① : t=" ": k=0
For i=1 To Len(s)
c=Mid(s, i, 1)
If c<>"," Then
②
Else
k=k+1
a(k)=Val(t)
t=""
End If
Next i
L=a(1): R=a(2)
i=3
Do While i<=k
If a(i)>R Then
result = result+"("+Str(L)+","+Str(R)+"),"
L=a(i): R=a(i+1)
R=a(i+1)
End If
③
Loop
result=result+"("+Str(L)+","+Str(R)+"),"
Text2. Text=result
End Sub