0

我想生成单词的组合。例如,如果我有以下列表:{cat, dog, horse, ape, hen, mouse} 那么结果将是 n(n-1)/2 cat dog horse ape hen mouse (cat dog) (dog horse) (马猿)(猿母鸡)(母鸡老鼠)(猫狗马)(狗马猿)(马猿母鸡)等

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

我的清单将是 500 长

4

2 回答 2

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)
于 2010-04-12T04:43:04.473 回答
1

假设你的列表是 arr = {cat, dog, horse, ape, hen, mouse} 那么你可以这样做:

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

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

于 2010-04-12T04:38:44.550 回答