Visual Basic(.NET)>随机化列表框选择(唯一)

时间:2017-05-06 13:59:47

标签: vb.net random listbox unique

我只想制作随机数发生器程序。它将用于挑选锦标赛对(如f.e.欧洲冠军联赛四分之一对)

GUI屏幕:http://i.imgur.com/jqBMJjt.png

我遇到了麻烦..当我试图制作选择器时,它运行良好>从列表框1(左侧)到listbox2(50%的listbox1项目),listbox3(50%的listbox1项目)..(左侧)但这些选择并不是唯一的。你可以在图像上看到一些重复(第二个列表框2x noob)。

我的部分代码:

Private Sub RandomiseListBox()
    Dim count As Integer = CarbonFiberListBox1.Items.Count
    Dim countt As Integer
    'countt = count / 2
    Dim item As String
    Dim itemz As New List(Of String)()
    Dim repeat As New List(Of String)()
    Dim aa, bb As Integer


    If Not count = 0 And ((count Mod 2) = 0) Then
        CarbonFiberListBox2.Items.Clear()
        CarbonFiberListBox3.Items.Clear()

        For index As Integer = 0 To countt - 1 Step 1
            item = Me.CarbonFiberListBox1.Items(Me.randomiser.Next(index, count))
            itemz.Add(item)
            'Me.CarbonFiberListBox1.Items.Remove(item)
            'Me.CarbonFiberListBox1.Items.Insert(index, item)
            Me.CarbonFiberListBox2.Items.Insert(index, item)
        Next index

        For index As Integer = 0 To countt - 1 Step 1
            For aa = 0 To bb = 999
                item = Me.CarbonFiberListBox1.Items(Me.randomiser.Next(index, count))
                If Not (itemz.Contains(item)) And Not (repeat.Contains(item)) Then
                    repeat.Add(item)
                    'Me.CarbonFiberListBox1.Items.Remove(item)
                    'Me.CarbonFiberListBox1.Items.Insert(index, item)
                    Me.CarbonFiberListBox3.Items.Insert(index, item)
                End If
            Next
        Next index

        'For index As Integer = 0 To countt - 1 Step 1

        'Next index
    ElseIf count > 0 Then
        'CarbonFiberButton4.Text = "ODD PARTICIPANTS!"
    Else
    End If
End Sub

我可以获得帮助吗?我认为这很容易。

1 个答案:

答案 0 :(得分:0)

也许这个小例子会给你一个想法。它的工作原理是从一个列表框中以随机顺序获取列表。请注意列表如何耗尽,因为项目被添加到其他列表框中,这会阻止重复项。

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    'some sample data
    ListBox1.DataSource = {"one", "two", "three", "four", "five", "six", "seven"}
    DoRandom()
End Sub

Private Shared prng As New Random
Private Sub DoRandom()
    ListBox2.Items.Clear()
    ListBox3.Items.Clear()
    Dim l As New List(Of String)
    'random order of items in ListBox1
    l.AddRange(ListBox1.Items.Cast(Of String).OrderBy(Function(s) prng.Next))
    'add half to lb2
    For x As Integer = 0 To l.Count \ 2
        ListBox2.Items.Add(l(0))
        l.RemoveAt(0)
    Next

    'remainder to lb3
    For x As Integer = 0 To l.Count - 1
        ListBox3.Items.Add(l(0))
        l.RemoveAt(0)
    Next
End Sub