字符串组合

时间:2010-04-12 03:58:47

标签: vb.net nested-loops

我想生成一个单词组合。例如,如果我有以下列表: {猫,狗,马,猿,母鸡,老鼠} 然后结果将是n(n-1)/ 2 猫狗马猿母鸡 (猫狗)(狗马)(马猿)(猿母鸡)(母鸡) (猫狗马)(狗马猿)(马猿母鸡)等

希望这是有道理的...我发现的一切都涉及排列

我的名单将是500长

2 个答案:

答案 0 :(得分:3)

试试这个! :

Public Sub test()

    Dim myAnimals As String = "cat dog horse ape hen mouse"

    Dim myAnimalCombinations As String() = BuildCombinations(myAnimals)

    For Each combination As String In myAnimalCombinations
        'Look on the Output Tab for the results!
        Console.WriteLine("(" & combination & ")")  
    Next combination


End Sub



Public Function BuildCombinations(ByVal inputString As String) As String()

    'Separate the sentence into useable words.
    Dim wordsArray As String() = inputString.Split(" ".ToCharArray)

    'A plase to store the results as we build them
    Dim returnArray() As String = New String() {""}

    'The 'combination level' that we're up to
    Dim wordDistance As Integer = 1

    'Go through all the combination levels...
    For wordDistance = 1 To wordsArray.GetUpperBound(0)

        'Go through all the words at this combination level...
        For wordIndex As Integer = 0 To wordsArray.GetUpperBound(0) - wordDistance

            'Get the first word of this combination level
            Dim combination As New System.Text.StringBuilder(wordsArray(wordIndex))

            'And all all the remaining words a this combination level
            For combinationIndex As Integer = 1 To wordDistance

                combination.Append(" " & wordsArray(wordIndex + combinationIndex))

            Next combinationIndex

            'Add this combination to the results
            returnArray(returnArray.GetUpperBound(0)) = combination.ToString

            'Add a new row to the results, ready for the next combination
            ReDim Preserve returnArray(returnArray.GetUpperBound(0) + 1)

        Next wordIndex

    Next wordDistance

    'Get rid of the last, blank row.
    ReDim Preserve returnArray(returnArray.GetUpperBound(0) - 1)

    'Return combinations to the calling method.
    Return returnArray

End Function

第一个功能就是向您展示如何调用第二个函数。这实际上取决于你如何获得500个列表 - 你可以将它复制并粘贴到动物名称上,或者你可以加载包含其中单词的文件。如果它不适合一行,你可以尝试:

    Dim myAnimals As New StringBulder 
    myAnimals.Append("dog cat ... animal49 animal50") 
    myAnimals.Append(" ") 
    myAnimals.Append("animal51 ... animal99") 
    myAnimals.Append(" ") 
    myAnimals.Append("animal100 ... animal150") 

等。

然后

Dim myAnimalCombinations As String() = BuildCombinations(myAnimals.ToString)

答案 1 :(得分:1)

说你的清单是arr = {猫,狗,马,猿,母鸡,鼠标} 然后你可以这样做:

for i = 0; i < arr.size; i++)
  for j = i; j < arr.size; j++)
    print i,j;

这个想法基本上是 - 对于每个项目,将它与列表中的每个其他项目配对。但是,为了避免重复(例如1,2和2,1),你不是每次都从头开始内部循环,而是从外循环的当前索引开始。