我想生成一个单词组合。例如,如果我有以下列表:{猫,狗,马,猿,母鸡,老鼠},那么结果将是n(n-1)/2猫狗马猿母鼠(猫狗)(狗马)(马猿)(猿母鸡)(母鼠)(猫狗马)(狗马猿)等等
我希望这使我发现的sense...everything包含了排列
我的单子会有500长
发布于 2010-04-12 12:43:04
试试这个!:
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-12 12:38:45
假设你的列表是arr ={猫,狗,马,猿,母鸡,老鼠},你可以这样做:
for i = 0; i < arr.size; i++)
for j = i; j < arr.size; j++)
print i,j;这个想法基本上是--对于每个项目,将其与列表中的其他项目配对。但是,为了避免重复(例如1,2和2,1),您不是每次都从头开始内部循环,而是从外部循环的当前索引开始。
https://stackoverflow.com/questions/2619805
复制相似问题