Vb.net all combinations

前端 未结 4 1104
南旧
南旧 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:31

    Want the input as strings? and no recursion? then here's the final solution, a simple adaptation of my previous sample:

        Dim Lines As New List(Of List(Of String))
        AddItem(Lines, "a ")
        AddItem(Lines, "b ")
        AddItem(Lines, "c1|c2|c3 ")
        AddItem(Lines, "d ")
        AddItem(Lines, "e1|e2")
        AddItem(Lines, "f ") ' etc
        Dim i As Integer
        Dim j As Integer
        Dim ItemnrInLine(Lines.Count - 1) As Integer
        Dim NrCombinations = 1
        For i = 0 To (Lines.Count - 1)
            ItemnrInLine(i) = 0
            NrCombinations *= Lines(i).Count
        Next
        ItemnrInLine(Lines.Count - 1) = -1 ' to get first combination as solution
        For i = 1 To NrCombinations
            ItemnrInLine(Lines.Count - 1) += 1
            For j = Lines.Count - 1 To 0 Step -1
                If ItemnrInLine(j) = Lines(j).Count Then
                    ItemnrInLine(j) = 0
                    ItemnrInLine(j - 1) += 1
                End If
            Next
            printOut(Lines, ItemnrInLine)
        Next
    
    Sub printOut(ByVal Lines As List(Of List(Of String)), ByVal ItemnrInLine() As Integer)
        Dim Result As String = ""
        For k = 0 To Lines.Count - 1
            Result = Result & Lines(k)(ItemnrInLine(k)).Trim & " "
        Next
        Debug.WriteLine(Result)
    End Sub
    
    Sub AddItem(ByVal Lines As List(Of List(Of String)), ByVal inputString As String)
        Dim words() As String = inputString.Split("|"c)
        Dim wordList As New List(Of String)
        For i As Integer = 0 To words.Count - 1
            wordList.Add(words(i))
        Next
        Lines.Add(wordList)
    End Sub
    

提交回复
热议问题