我有以下代码来生成一个小列表的字符串的组合,并希望适应这个超过300个字符串words.Can任何人都可以建议如何改变此代码或使用一种不同的方法。适应组合代码大列表
Public Class combinations
Public Shared Sub main()
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
Console.ReadLine()
End Sub
Public Shared 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
End Class
'
CHANGES //
对于wordDistance = 1要在代码inputList.Count.ToString/2
Dim count = inputList.Count.ToString
'Go through all the words at this combination level...
For wordIndex As Integer = 0 To inputList.Count.ToString - wordDistance
'Get the first word of this combination level
combination.Add(inputList.Item(wordIndex))
'And all all the remaining words a this combination level
For combinationIndex As Integer = 1 To wordDistance
combination.Add(" " & inputList.Item(wordIndex + combinationIndex))
Next combinationIndex
'Add this combination to the results
If Not wordsList.Contains(combination) Then
wordsList.Add(combination.ToString)
End If
'Add a new row to the results, ready for the next combination
'ReDim Preserve returnArray(returnArray.GetUpperBound(0) + 1)
Next wordIndex
Next wordDistance
你为什么问这个问题?您是否遇到性能问题?它不会返回预期的结果吗? – 2010-04-12 15:23:48
这是一个性能问题。事实上,它的运行时间很长,我不得不停止代码,因为如果可能的话,目标时间不到一分钟甚至30秒。因此,例如,我有一个335字符串单词列表,它只是花了很长时间 – vbNewbie 2010-04-12 15:37:05
除了我的答案下面,也可能有您的算法的问题,所以如果我的建议并不能帮助它可能值得重写它作为伪代码并将其重新设置为一个语言不可知的问题,可能会被很多人看到(VB.Net标记在这里似乎并不受欢迎) – 2010-04-12 18:18:00