Vb.net all combinations

前端 未结 4 1127
南旧
南旧 2021-01-16 16:18

I have 6 items which have to be combinated,

items listed: ( this is an example)

  • Ape
  • Cow
  • Deer | Small deer | Big deer
4条回答
  •  长发绾君心
    2021-01-16 16:43

    Here's a recursive solution for VB 2010 (probably not very good performance-wise when there are a lot of combinations, but it's a start):

    Function GetCombinations(items As String()(), Optional index As Integer = 0) As List(Of String())
        Dim combinations As New List(Of String())
        Dim lastIndex = items.Count - 1
        Select Case index
            Case Is < 0, Is > lastIndex
                Throw New ArgumentException("index should be 0 or greater")
            Case lastIndex
                For Each item In items(index)
                    combinations.Add({item})
                Next
            Case Else
                Dim nextCombinations = GetCombinations(items, index + 1)
                For Each item In items(index)
                    For Each nextCombination In nextCombinations
                        combinations.Add({item}.Concat(nextCombination).ToArray)
                    Next
                Next
        End Select
        Return combinations
    End Function
    

    Test code:

    Dim items = {({"Ape"}), ({"Cow"}), ({"Deer", "Small deer", "Big deer"}), ({"Sheep"}), ({"Mouse", "Black Mouse", "White mouse"})}
    For Each combination In GetCombinations(items)
        Console.WriteLine(String.Join(", ", combination))
    Next
    

    Test outputs:

    Ape, Cow, Deer, Sheep, Mouse
    Ape, Cow, Deer, Sheep, Black Mouse
    Ape, Cow, Deer, Sheep, White mouse
    Ape, Cow, Small deer, Sheep, Mouse
    Ape, Cow, Small deer, Sheep, Black Mouse
    Ape, Cow, Small deer, Sheep, White mouse
    Ape, Cow, Big deer, Sheep, Mouse
    Ape, Cow, Big deer, Sheep, Black Mouse
    Ape, Cow, Big deer, Sheep, White mouse
    

提交回复
热议问题