none
How to select a random element of an array? RRS feed

  • Question

  • I am attempting to select a random element of an array every time I click a button.

    This is my array-  Dim numbers = New Color() {red, green, blue, white}

    How do I randomly select one?

    Thursday, December 21, 2017 4:14 PM

Answers

  • I am attempting to select a random element of an array every time I click a button.

    This is my array-  Dim numbers = New Color() {red, green, blue, white}

    How do I randomly select one?

    Hi

    Maybe something like this. Needs Label1 and Button1 on Form

    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim numbers() As Color = {Color.Red, Color.Green, Color.Blue, Color.White}
      Dim rand As New Random
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    	Label1.BackColor = numbers(rand.Next(0, numbers.Count))
      End Sub
    End Class


    Regards Les, Livingston, Scotland


    Thursday, December 21, 2017 4:32 PM

All replies

  • I am attempting to select a random element of an array every time I click a button.

    This is my array-  Dim numbers = New Color() {red, green, blue, white}

    How do I randomly select one?

    Hi

    Maybe something like this. Needs Label1 and Button1 on Form

    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim numbers() As Color = {Color.Red, Color.Green, Color.Blue, Color.White}
      Dim rand As New Random
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    	Label1.BackColor = numbers(rand.Next(0, numbers.Count))
      End Sub
    End Class


    Regards Les, Livingston, Scotland


    Thursday, December 21, 2017 4:32 PM
  • Thanks Leshay Your code seemed to work fine without the options on. Also I think you meant numbers.Length instead of number.Count.                                     


    Thursday, December 21, 2017 4:42 PM
  • Thanks Leshay Your code seemed to work fine without the options on. Also I think you meant numbers.Length instead of number.Count.                                     


    Hi

    The Numbers.Length is, I believe, a better option, but Numbers.Count also does return the correct value.




    Regards Les, Livingston, Scotland

    Thursday, December 21, 2017 5:30 PM
  • Building on leshay's response

        Private Shared PRNG As New Random
        Dim allColors As List(Of Color) = (From c In [Enum].GetValues(GetType(KnownColor))
                                           Let sc As Color = Color.FromKnownColor(DirectCast(c, KnownColor))
                                           Select sc).ToList
    
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Label1.BackColor = allColors(PRNG.Next(0, allColors.Count))
            Label1.ForeColor = GetContrastColor(Label1.BackColor)
        End Sub
    
        ''' <summary>
        ''' used to calculate a foreground color based on background color
        ''' </summary>
        ''' <param name="backColor">background color</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function GetContrastColor(backColor As Color) As Color
            'YIQ method to create a contrasting color
            'http://24ways.org/2010/calculating-color-contrast/
    
            Dim rv As Color
    
            Dim R As Integer = backColor.R
            Dim G As Integer = backColor.G
            Dim B As Integer = backColor.B
    
            Dim yiq As Integer = ((R * 299) + (G * 587) + (B * 114)) \ 1000
    
            rv = If(yiq >= 128, Color.Black, Color.White)
    
            Return rv
        End Function
    


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it" - MSDN User JohnWein

    Thursday, December 21, 2017 5:31 PM
  • Thanks Leshay Your code seemed to work fine without the options on. Also I think you meant numbers.Length instead of number.Count.                                     


    I think that "count" was added with a certain framework. "Length" is a little bit from the stone age but still on some very old classes like string and array. Normally it is Count, therefore those busy with this don't think. They click the C and then probably use intelisense. 

     

    Success
    Cor

    Thursday, December 21, 2017 6:13 PM
  • Hello,

    It seems that leshay's post can answer your question, please remember to close the post as answer, it is beneficial to other community members who face the same issue.

    Thanks for your understanding.

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, December 22, 2017 7:53 AM
    Moderator
  • I am attempting to select a random element of an array every time I click a button.

    This is my array-  Dim numbers = New Color() {red, green, blue, white}

    How do I randomly select one?

    I chose to put this in a class so that it's more easily reusable i the future.

    I set the class up to be generic class where you can use any value type. It returns a nullable(of that type) because of an option that I put in there: The ability to always choose one that's not so far been chosen:

    Public NotInheritable Class MyCollection(Of T As Structure)
        Private _original() As T
        Private _rand As Random
        Private _used As List(Of T)
    
        Public Sub New(ByVal collection As IEnumerable(Of T))
    
            If collection Is Nothing Then
                Throw New ArgumentNullException("Collection", "The collection cannot be null." & vbCrLf)
    
            ElseIf collection.Count = 0 Then
                Throw New ArgumentOutOfRangeException("Collection", "The collection cannot be empty." & vbCrLf)
    
            Else
                _original = collection.ToArray
                _rand = New Random
                _used = New List(Of T)
            End If
    
        End Sub
    
        Public Function _
            GetRandomMember(Optional ByVal okToReselect As Boolean = True) As Nullable(Of T)
    
            Dim retVal As Nullable(Of T) = Nothing
    
            Dim randIndex As Integer = _rand.Next(0, _original.Count)
    
            If okToReselect Then
                retVal = _original(randIndex)
            Else
                If _used.Count < _original.Count Then
                    Do While _used.Contains(_original(randIndex))
                        randIndex = _rand.Next(0, _original.Count)
                    Loop
    
                    _used.Add(_original(randIndex))
    
                    retVal = _original(randIndex)
                End If
            End If
    
            Return retVal
    
        End Function
    End Class

    To use it, have  a look at the test that I ran for it where I give just five values to choose from but I run it six times:

    Public Class Form1
        Private collection As MyCollection(Of Integer)
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            Dim numbers() As Integer = (Enumerable.Range(1, 5)).ToArray
    
            collection = New MyCollection(Of Integer)(numbers)
    
            TestMethod()
    
        End Sub
    
        Private Sub TestMethod()
    
            For i As Integer = 1 To 6
                Dim randomNumber As Nullable(Of Integer) = collection.GetRandomMember(False)
    
                If randomNumber.HasValue Then
                    MessageBox.Show(randomNumber.Value.ToString, "Loop Number: " & i.ToString)
                Else
                    MessageBox.Show("The return value is null.", "Loop Number: " & i.ToString)
                End If
            Next
    
        End Sub
    
    End Class

    I hope it helps.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, December 23, 2017 1:15 PM
  • Also I think you meant numbers.Length instead of number.Count.

    Either one is fine - they're both the same.

    An array implements several interfaces:

    https://msdn.microsoft.com/en-us/library/system.array(v=vs.110).aspx

    If you'll look at that documentation, one of them is the ICollection interface:

    https://msdn.microsoft.com/en-us/library/system.collections.icollection(v=vs.110).aspx

    Lastly, notice in that last link that one of the properties is the .Count property. That's where it comes from.

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, December 23, 2017 1:20 PM