【发布时间】:2014-02-25 05:14:48
【问题描述】:
在 VB.NET 中,如何从列表中列出所有可能的组合。我希望能够使用传入参数的方法来指定每个组合中的项目数。就我而言,我只想要 2 个。我不想以不同的顺序看到相同的组合。我想将此信息记录在列表框中。我已经尝试过其他帖子的请求,但它们似乎对我不起作用。
感谢您的帮助
【问题讨论】:
标签: vb.net list combinations
在 VB.NET 中,如何从列表中列出所有可能的组合。我希望能够使用传入参数的方法来指定每个组合中的项目数。就我而言,我只想要 2 个。我不想以不同的顺序看到相同的组合。我想将此信息记录在列表框中。我已经尝试过其他帖子的请求,但它们似乎对我不起作用。
感谢您的帮助
【问题讨论】:
标签: vb.net list combinations
这是一种快速而肮脏的方法。这是非常低效的,绝不是“最好”的方式。一旦代码“停止”,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
【讨论】: