2014-02-24 68 views
0

在VB.NET中,如何列出列表中的所有可能組合。我希望能夠使用傳遞參數的方法來指定每個組合中的項目數。在我的情況下,我只想要2.我不想以不同的順序看到相同的組合。我想將這些信息記錄在列表框中。我嘗試了其他帖子的要求,但他們似乎不適合我。列出VB.NET中的所有組合

感謝您的任何幫助

回答

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 
+0

這完全不是家庭作業。我是一個業餘愛好者程序員。我不會否認我有多年的經驗。我將檢查出HashSet類,因爲這是我需要的。謝謝 –

+0

我會喜歡,但我沒有足夠的聲譽。 –

+0

請你可以給我一些代碼。我堅持我如何聲明包含組合的數組。謝謝 –