0

I want to call a random color between 8 different colors and display it in a label as its backcolor in Visual Basic. How can I display the colors without repeating a color that has been called out on a specific label?

For example, if color red is called out and displayed in labelA1, how can I make sure that color red won't be called out and displayed in labelB1, labelC1 or labelD1 but can be called out in labelA13 or labelB16?

Below is a picture to help understand the example above.

enter image description here

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Wilfred
  • 19
  • 1
  • Possible duplicate of [Unique (non-repeating) random numbers in O(1)?](https://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1) – Robert Kock Oct 26 '18 at 13:31
  • Look at shuffle algorithm implementations. You don't want "random" you want a shuffle. – Bob77 Oct 27 '18 at 21:12

1 Answers1

0

Use this code to make a list of colors then knock them off the list every time one is used.

Private Function RandomizeLabelColors() As Integer
    Randomize()
    Dim listOfColors As List(Of Color) = {Color.Red, Color.Blue, Color.Green, Color.Orange}.ToList
    Dim labels As List(Of Label) = {Label1, Label2, Label3, Label4, Label5, Label6, Label7, Label8,
        Label9, Label10, Label11, Label12, Label13, Label14, Label15, Label16}.ToList
    Dim i As Integer = 0
    Do Until listOfColors.Count = 0
        Dim targetIndex As Integer = Int(Rnd() * listOfColors.Count)
        labels(i).BackColor = listOfColors(targetIndex)
        labels(i + 4).BackColor = listOfColors(targetIndex)
        labels(i + 8).BackColor = listOfColors(targetIndex)
        labels(i + 12).BackColor = listOfColors(targetIndex)
        listOfColors.RemoveAt(targetIndex)
        i += 1
    Loop
    Return 0
End Function

I have my labels in a 4x4 grid.

-Mg

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Marco
  • 53
  • 1
  • 6