在VB.NET中,如何列出列表中的所有可能组合。我希望能够使用传递参数的方法来指定每个组合中的项目数。在我的情况下,我只想要2.我不希望以不同的顺序看到相同的组合。我想在列表框中记录这些信息。我已尝试过其他帖子的请求,但它们似乎对我不起作用。
感谢您的帮助
答案 0 :(得分:0)
这是一种快速而肮脏的方式。这是非常低效的,绝不是“最好的”方式。代码完成“停止”后,uniqueResults
将包含您要添加到列表框中的项目。
Module Module1
Sub Main()
Dim source As New List(Of String)({"cat", "dog", "hamster", "goat"})
Dim results As List(Of List(Of String)) = Combine(source, 3)
Dim uniqueResults As List(Of String) = Filter(results)
stop
End Sub
''' <summary>
''' Builds an N length list of all possible combinations of Source
''' </summary>
''' <param name="source">a list of strings containing the possible items</param>
''' <param name="length">the length of the list of items to return</param>
Private Function Combine(source As List(Of String), length As Integer) As List(Of List(Of String))
Dim ret As New List(Of List(Of String))
Combine(source, length, New List(Of String), ret)
Return ret
End Function
''' <summary>
''' Recursivly builds an N length list of all possible combinations of Source
''' </summary>
''' <param name="source">a list of strings containing the possible items</param>
''' <param name="length">the number of items remaining to add to the list</param>
''' <param name="value">the current list being built</param>
''' <param name="output">a list of all possible combinations</param>
Private Sub Combine(source As List(Of String), length As Integer, value As List(Of String), output As List(Of List(Of String)))
For i As Integer = 0 To source.Count - 1
value.Add(source(i))
If length <= 1 Then
'Console.WriteLine(String.Join(", ", value))
output.Add(New List(Of String)(value))
Else
Combine(source, length - 1, value, output)
End If
value.RemoveAt(value.Count - 1)
Next
End Sub
''' <summary>
''' returns only unique patterns
''' </summary>
''' <param name="list"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function Filter(list As List(Of List(Of String))) As List(Of String)
Dim found As New HashSet(Of String)
For Each item As List(Of String) In list
Dim temp As New List(Of String)(item)
temp.Sort()
Dim s As String = String.Join(", ", temp)
If Not found.Contains(s) Then
found.Add(s)
End If
Next
Return New List(Of String)(found)
End Function
End Module