user3587953
user3587953

Reputation: 11

VB Array to produce random values

What I want to do is create an application that has an array that is randomly generated according to the users specifications.

for example they specify the dimensions into a textbox which then creates the specific size

I then want to be able to press another button 'PlayButton' which randomly splits the already generated values into 2 different list boxes where it is added up and who ever has the highest value is the winner

this is the code that I have already:

Public Sub NewButton_Click(sender As Object, e As EventArgs) Handles NewButton.Click
    Try
        Row = ColumnBox.Text
        Column = RowBox.Text

    Catch ex As InvalidCastException
        MessageBox.Show("Dimensions are not valid")
    End Try
    Dim Array As Random = New Random(DateTime.Now.Millisecond)
    Dim oTextbox As Label
    For index1 As Integer = 0 To (Row - 1) Step 1
        For index2 As Integer = 0 To (Column - 1) Step 1
            oTextbox = New Label()
            With oTextbox
                .Name = "TextBox" & index1.ToString & index2.ToString
                .Text = Array.Next(100)
                .Width = Me.Width / 8
                .Left = index1 * (Me.Width / 8)
                .Top = index2 * .Height
            End With
            Panel1.Controls.Add(oTextbox)
        Next index2
    Next index1

    ColumnBox.Text = "Columns"
    RowBox.Text = "Rows"
End Sub

Upvotes: 1

Views: 107

Answers (1)

SysDragon
SysDragon

Reputation: 9888

Before I begin, I strongly recommend you to use Option Strict On in your project option.

You can fill an array doing something like this:

Dim arr(,) As Integer

Sub NewButton_Click(sender As Object, e As EventArgs) Handles NewButton.Click
    Dim iRowLen, iColLen As Integer
    Dim rdm As New Random()

    If Integer.TryParse(RowBox.Text, iRowLen) AndAlso Integer.TryParse(ColumnBox.Text, iColLen) Then
        ReDim arr(iRowLen - 1, iColLen - 1)

        For i As Integer = 0 To iRowLen - 1
            For j As Integer = 0 To iColLen - 1
                arr(i, j) = rdm.Next(100)
            Next
        Next
    Else
        MessageBox.Show("Dimensions are not valid")
    End If
End Sub

Then you have an array filled with your random values. To distribute the values in two groups you can do something like this:

Sub PlayButton_Click(sender As Object, e As EventArgs) Handles PlayButton.Click
    Dim rdm As New Random()
    Dim lst As New List(Of Integer)(arr)

    While lst.Count > 0
        Dim index As Integer = rdm.Next(lst.Count)

        If lst.Count Mod 2 = 0 Then
            ' Do something with the value
        Else
            ' Do something with the value
        End If

        lst.Remove(index)
    End While        
End Sub

The above code will select random values from the array. The IfElse part will alternate to add the random value to one place or another. You can add the values where you want.

Upvotes: 1

Related Questions