1

Goal: I want to grab 2 strings from an array at random and then put them together.

Problem: When I click button1, textbox1 shows one of the colors back-to-back

(BlackBlack, BlueBlue, BrownBrown, GrayGray, GreenGreen) ☒

instead of showing 2 different colors back-to-back.

(BlackBlue, BlueBrown, BrownGray, GrayGreen, GreenOrange) ☑

This is my code (so far):

        string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };

    private void button1_Click(object sender, EventArgs e)
    {
        string FirstColor;
        string SecondColor;
        FirstColor = Colors[new Random().Next(0, Colors.Length)];
        SecondColor = Colors[new Random().Next(0, Colors.Length)];
        textBox1.Text = FirstColor + SecondColor;
    }
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Owen
  • 321
  • 2
  • 12

2 Answers2

2
 string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };

    private Random random = new Random();

    private void button1_Click(object sender, EventArgs e)
    {
        string FirstColor;
        string SecondColor;
        FirstColor = Colors[random.Next(0, Colors.Length)];          
        do
        {
            SecondColor = Colors[random.Next(0, Colors.Length)];

        } while (!FirstColor.Equals(SecondColor));
        textBox1.Text = FirstColor + SecondColor;
    }
Nalaka
  • 1,165
  • 7
  • 12
0

The random number generator is seeded by the current timestamp when it's created. If you create two in immediate succession, they'll have the same seed. Instead create one, store it in a field, and reuse it.

string[] Colors = { "Black", "Blue", "Brown", "Gray", "Green", "Orange", "Pink", "Purple", "Red", "White", "Yellow" };

private Random random = new Random();

private void button1_Click(object sender, EventArgs e)
{
    string FirstColor;
    string SecondColor;
    FirstColor = Colors[random.Next(0, Colors.Length)];
    SecondColor = Colors[random.Next(0, Colors.Length)];
    textBox1.Text = FirstColor + SecondColor;
}
Samuel Neff
  • 73,278
  • 17
  • 138
  • 182