vb实现数组组合输出
数组元素组合输出,比如数组1,2,3,4我要提出其中的3个数的所有组合,不用排序,不能重复,可以说1,2,3;1,2,4;1,3,4;2,3,4;等,我的数组是6个元素到...
数组元素组合输出,比如数组1,2,3,4我要提出其中的3个数的所有组合,不用排序,不能重复,可以说1,2,3;1,2,4;1,3,4;2,3,4;等,我的数组是6个元素到13个元素,数组内容要求用文本框输入,也就是说出现13个文本框,然后输入大于6的N个数,然后组合输出。
展开
1个回答
展开全部
如孝橡果是固定数目的元素组合,那么用数个For循环嵌套来解决是很简单的,也不用判断重复。输入用的是文本框控件数旅慎正组,输出的文本框的MultiLine属性要设为True,这样才能显示多行。从13个元素中取6个不重拆悔复元素的组合共有1716个。 Private Sub Command1_Click() Dim a(0 To 12) As Integer Dim i As Integer For i = 0 To 12 a(i) = Text(i).Text Next Text1.Text = s(a) End Sub Private Function s(a() As Integer) As String Dim i1 As Integer Dim i2 As Integer Dim i3 As Integer Dim i4 As Integer Dim i5 As Integer Dim i6 As Integer Dim c As Integer Dim r As String For i1 = 0 To 12 - 5 For i2 = i1 + 1 To 12 - 4 For i3 = i2 + 1 To 12 - 3 For i4 = i3 + 1 To 12 - 2 For i5 = i4 + 1 To 12 - 1 For i6 = i5 + 1 To 12 r = r & a(i1) & "," & a(i2) & "," & a(i3) & "," & a(i4) & "," & a(i5) & "," & a(i6) & vbCrLf c = c + 1 DoEvents Next Next Next Next Next Next MsgBox c s = r End Function 但是这种算法的缺点是只能用于固定的数目,而且数目多的话程序写起来也很麻烦。下面再给一个可以算出任意数目元素组合的代码。 Private Sub Command1_Click() Dim a(0 To 12) As Integer Dim i As Integer For i = 0 To 12 a(i) = Text(i).Text Next Text1.Text = s(a, 13, 6) End Sub Private Function s(a() As Integer, ByVal n As Integer, ByVal m As Integer) As String Dim b() As Integer Dim r As String Dim c As Integer ReDim b(0 To m - 1) ss a, n, b, m, 0, r, c MsgBox c s = r End Function Private Sub ss(a() As Integer, ByVal n As Integer, b() As Integer, ByVal m As Integer, ByVal d As Integer, r As String, c As Integer) Dim i As Integer If m = 0 Then For i = 0 To UBound(b) - 1 r = r & a(b(i)) & "," Next r = r & a(b(UBound(b))) & vbCrLf c = c + 1 Exit Sub End If If m > n Or n <= 0 Then Exit Sub b(d) = n - 1 ss a, n - 1, b, m - 1, d + 1, r, c ss a, n - 1, b, m, d, r, c End Sub
采纳哦
采纳哦
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询