我想生成單詞的組合。例如,如果我有以下列表: {貓,狗,馬,猿,母雞,小鼠} 然後結果將是n(n-1)/ 2 貓狗馬猿母雞鼠標 (貓狗)狗馬)(馬猿)(APE母雞)(母雞鼠標) (貓狗馬)(狗馬猿)(馬猿母雞)等字符串組合
希望這是有道理的......一切,我發現涉及排列
我的清單將是一個長500
我想生成單詞的組合。例如,如果我有以下列表: {貓,狗,馬,猿,母雞,小鼠} 然後結果將是n(n-1)/ 2 貓狗馬猿母雞鼠標 (貓狗)狗馬)(馬猿)(APE母雞)(母雞鼠標) (貓狗馬)(狗馬猿)(馬猿母雞)等字符串組合
希望這是有道理的......一切,我發現涉及排列
我的清單將是一個長500
試試這個! :
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)
說你的列表是ARR = {貓,狗,馬,猿,母雞,鼠標} 然後,你可以這樣做:
for i = 0; i < arr.size; i++)
for j = i; j < arr.size; j++)
print i,j;
這個想法基本上是 - 對於每個項目,將它與列表上的每個其他項目配對。但是,爲了避免重複(例如1,2和2,1),每次除了外循環的當前索引外,不要從頭開始內部循環。
這隻會打印所有組合對,這不是他想要做的。 – 2012-05-10 16:59:05
有什麼問題??? – 2010-04-12 04:05:01
他是否想要實現包含2^n-1元素的列表的關閉? – zsong 2010-04-12 04:41:28