【问题标题】:Generate permutations from listboxes从列表框生成排列
【发布时间】:2018-01-20 17:47:12
【问题描述】:

我有 4 个列表框,每种类型一个(头饰、内衬衫、外衬衫、裤子)。

一个列表框将包含单一类型的元素(例如帽子、红色和太阳帽、绿色...)

我希望能够从 4 个列表框中生成所有元素的所有排列,并将结果保存到文本文件中。

因此,例如,输出将包含:

  • 帽子,红色 | t恤,棕色| 高分辨率照片| CLIPARTO毛衣,棕色| 高分辨率照片| CLIPARTO裤子,蓝色
  • 太阳帽,蓝色 | t恤,棕色| 高分辨率照片| CLIPARTO夹克,橙色| 高分辨率照片| CLIPARTO短裤,灰色

我尝试查看此post,将列表框转换为数组,然后生成排列。但是,我无法将其保存到文件中,或者保存到列表框然后保存到文件中。

那么如何从四个列表框生成所有排列?

【问题讨论】:

    标签: vb.net listbox permutation


    【解决方案1】:

    这两个程序会做你想做的事。虽然,如果这不仅仅是学校作业,我建议不要使用列表框作为排列的数据源,而是为每个对象(帽子、衬衫、套头衫和裤子)创建一个类。然后,每个人都可以拥有自己的属性,例如库存代码、描述、颜色、尺寸、订单号、供应商等。然后,从描述、颜色和尺寸生成您想要的每个项目的详细信息字符串,最后从每个项目的详细信息字符串。当然,最终你会更好地使用数据库,但那是开发程序的更远距离。

    Private Function GeneratePermutations() As List(Of String)
        Dim permList As New List(Of String)
        For Each hat As String In ListBox1.Items
            For Each shirt As String In ListBox2.Items
                For Each jumper As String In ListBox3.Items
                    For Each trousers As String In ListBox4.Items
                        permList.Add(hat & "," & shirt & "," & jumper & "," & trousers)
                    Next
                Next
            Next
        Next
        Return permList
    End Function
    
    Private Sub SaveFile(permlist As List(Of String), filename As String)
        If File.Exists(filename) Then
            Dim result As DialogResult = MessageBox.Show("File Exists, Overwrite? Y/N", "File Exists", MessageBoxButtons.YesNo)
            If result = DialogResult.No Then
                Exit Sub
            End If
        End If
        Try
            Using sr As New StreamWriter(filename)
                For Each line As String In permlist
                    sr.WriteLine(line)
                Next
            End Using
        Catch ex As Exception
            MessageBox.Show("Exception:" & ex.Message & vbCrLf & "Inner Exception :" & ex.InnerException.Message)
        End Try
    End Sub
    

    使用示例

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim permutationList As New List(Of String)
        For i As Integer = 1 To 5
            ListBox1.Items.Add("Hat" & i.ToString)
            ListBox2.Items.Add("Shirt" & i.ToString)
            ListBox3.Items.Add("Jumper" & i.ToString)
            ListBox4.Items.Add("Trousers" & i.ToString)
        Next
        permutationList = GeneratePermutations()
        SaveFile(permutationList, "K:\perms.txt")
    End Sub
    

    这些行..

    permutationList = GeneratePermutations()
    SaveFile(permutationList, "K:\perms.txt")
    

    可以进一步缩短为

    SaveFile(GeneratePermutations, "K:\perms.txt")
    

    那么下面的行就不需要了

    Dim permutationList As New List(Of String)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多