Link to home
Start Free TrialLog in
Avatar of backflash
backflash

asked on

Generating Combinations in VB5

Does anyone have a routine for generating each combination of a given group of numbers.

Example:
6 numbers has 6 groups of 5 numbers

1 2 3 4 5
1 2 3 4 6
1 3 4 5 6
1 2 4 5 6
1 2 3 5 6
2 3 4 5 6



Avatar of AzraSound
AzraSound
Flag of United States of America image

i take it that the algorithm states the numbers in the group must be in ascending order?
add two textboxes to hold the values (e.g. 5 and 6) and another textbox that is set to multiline to display the results.  add a command button that will execute the code:


Option Explicit

Private Sub MchoseN(ByVal N As Integer, ByVal first_allowed As Integer, ByVal last_allowed As Integer, ByVal solutions As Collection)
    Dim i As Integer
    Dim txt As String
    Dim partial_solutions As Collection

    If N < 1 Then

    ElseIf N > last_allowed - first_allowed + 1 Then

    ElseIf N = last_allowed - first_allowed + 1 Then

        txt = Format$(first_allowed)
        For i = first_allowed + 1 To last_allowed
            txt = txt & " " & Format$(i)
        Next i
        solutions.Add txt
    Else
        Set partial_solutions = New Collection
        If N = 1 Then
            partial_solutions.Add ""
        Else
            MchoseN N - 1, first_allowed + 1, last_allowed, partial_solutions
        End If

        For i = 1 To partial_solutions.Count
            solutions.Add Format$(first_allowed) & _
                " " & partial_solutions(i)
        Next i

        Set partial_solutions = New Collection
        MchoseN N, first_allowed + 1, last_allowed, partial_solutions

        For i = 1 To partial_solutions.Count
            solutions.Add partial_solutions(i)
        Next i
    End If
End Sub
Private Sub Command1_Click()
    Dim solutions As Collection
    Dim i As Integer
    Dim txt As String

    Set solutions = New Collection
    MchoseN CInt(txtN.Text), 1, CInt(txtM.Text), solutions

    For i = 1 To solutions.Count
        txt = txt & solutions(i) & vbCrLf
    Next i

    txtResult.Text = txt
    lblSolutions.Caption = Format$(solutions.Count)
End Sub

Private Sub Form_Resize()
    Dim hgt As Single

    hgt = ScaleHeight - txtResult.Top
    If hgt < 120 Then hgt = 120
    txtResult.Move 0, txtResult.Top, ScaleWidth, hgt
End Sub

ASKER CERTIFIED SOLUTION
Avatar of GivenRandy
GivenRandy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Unicorn061399
Unicorn061399

Why do u need a number generating algoritm? By simply assigning the values to an array u generate less code.
Or is this an arithmic question on binary logic or something?