下面是VB 2010遞歸解決方案(可能不是很好的表現,明智的,當有很多的組合,但它是一個開始):
Function GetCombinations(items As String()(), Optional index As Integer = 0) As List(Of String())
Dim combinations As New List(Of String())
Dim lastIndex = items.Count - 1
Select Case index
Case Is < 0, Is > lastIndex
Throw New ArgumentException("index should be 0 or greater")
Case lastIndex
For Each item In items(index)
combinations.Add({item})
Next
Case Else
Dim nextCombinations = GetCombinations(items, index + 1)
For Each item In items(index)
For Each nextCombination In nextCombinations
combinations.Add({item}.Concat(nextCombination).ToArray)
Next
Next
End Select
Return combinations
End Function
測試代碼:
Dim items = {({"Ape"}), ({"Cow"}), ({"Deer", "Small deer", "Big deer"}), ({"Sheep"}), ({"Mouse", "Black Mouse", "White mouse"})}
For Each combination In GetCombinations(items)
Console.WriteLine(String.Join(", ", combination))
Next
測試輸出:
Ape, Cow, Deer, Sheep, Mouse
Ape, Cow, Deer, Sheep, Black Mouse
Ape, Cow, Deer, Sheep, White mouse
Ape, Cow, Small deer, Sheep, Mouse
Ape, Cow, Small deer, Sheep, Black Mouse
Ape, Cow, Small deer, Sheep, White mouse
Ape, Cow, Big deer, Sheep, Mouse
Ape, Cow, Big deer, Sheep, Black Mouse
Ape, Cow, Big deer, Sheep, White mouse
在這最後一種情況下,你想要9行輸出? – Martin