Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all real combinations in VB .NET

Tags:

vb.net

I need to generate all combinations (not permutations) in VB .NET, I've been search and all I found is for permutations (some says combinations but when I was try it, all are permutations).

What I need is to generate combinations from string array:

Dim data_array As String() = {"one", "two", "three", "four", "five", "six"}

I need that:

If I say just 1 length, it must returns:

one
two
three
four
five
six

If I say 2 length, it must returs:

oneone
onetwo
onethree
onefour
... etc ...
twoone
twotwo
twothree
... etc ...

And continues til end with all combinations.

If I say more length do it as well.

like image 776
Minion Avatar asked Feb 20 '23 23:02

Minion


2 Answers

You say you want to generate all combinations but it looks to me like to are trying to generate all permutations.

You might try to do it recursively if you wish. If you just want to generate combinations then test the Root parameter to see if it contains myStr before appending it.

Public Class Form1
    Dim data_array As String() = {"one", "two", "three", "four", "five", "six"}
    Dim buffer As New List(Of String)

Public Sub Permute(ByVal Root As String, ByVal Depth As Integer, ByVal Buffer As List(Of String))

    For Each myStr As String In data_array

            If Depth <= 1 Then
                Buffer.Add(Root + myStr)
            Else
                Permute(Root + myStr, Depth - 1, Buffer)
            End If

    Next

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Permute("", 2, buffer)
End Sub
End Class
like image 138
deadlyvices Avatar answered Mar 01 '23 15:03

deadlyvices


This should returns all combinations of said depth in a IEnumerable(Of String)

 Function GetCombinations(ByVal depth As Integer, ByVal values As String()) As IEnumerable(Of String)
        If depth > values.Count + 1 Then Return New List(Of String)
        Dim result = New List(Of String)

        For i = 0 To depth - 1
            For y = 0 To values.Count - 1
                If i = 0 Then
                    result.Add(values(y))
                Else
                    result.Add(values(i - 1) + values(y))
                End If
            Next
        Next
        Return result
    End Function

Edit:

Example usage:

        Dim data_array As String() = {"1", "2", "3", "4", "5", "6"}
        Dim reslt = GetCombinations(2, data_array)
like image 20
Alex Avatar answered Mar 01 '23 17:03

Alex