我需要在VB .NET中生成所有组合(不是排列),我一直在搜索,我找到的只是排列(有些人说组合,但是当我尝试它时,所有都是排列)。
我需要的是从字符串数组生成组合:
Dim data_array As String() = {"one", "two", "three", "four", "five", "six"}
我需要:
如果我只说一个长度,它必须返回:
one
two
three
four
five
six
如果我说2长度,它必须回复:
oneone
onetwo
onethree
onefour
... etc ...
twoone
twotwo
twothree
... etc ...
并继续以所有组合结束。
如果我说更多长度,也可以。
答案 0 :(得分:5)
你说你想要生成所有组合,但我认为它试图生成所有排列。
如果您愿意,可以尝试递归地执行此操作。如果您只想生成组合,那么在附加它之前测试Root参数以查看它是否包含myStr。
Public Class Form1
Dim data_array As String() = {"one", "two", "three", "four", "five", "six"}
Dim buffer As New List(Of String)
Public Sub Permute(ByVal Root As String, ByVal Depth As Integer, ByVal Buffer As List(Of String))
For Each myStr As String In data_array
If Depth <= 1 Then
Buffer.Add(Root + myStr)
Else
Permute(Root + myStr, Depth - 1, Buffer)
End If
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Permute("", 2, buffer)
End Sub
End Class
答案 1 :(得分:1)
这应返回IEnumerable(Of String)
Function GetCombinations(ByVal depth As Integer, ByVal values As String()) As IEnumerable(Of String)
If depth > values.Count + 1 Then Return New List(Of String)
Dim result = New List(Of String)
For i = 0 To depth - 1
For y = 0 To values.Count - 1
If i = 0 Then
result.Add(values(y))
Else
result.Add(values(i - 1) + values(y))
End If
Next
Next
Return result
End Function
编辑:
使用示例:
Dim data_array As String() = {"1", "2", "3", "4", "5", "6"}
Dim reslt = GetCombinations(2, data_array)