简体   繁体   中英

how to generate a random numbers...? in c#

I have a 2d arrays button [5,5] all blue color...how to randomly generate 5 red button in the array...?

int Rows = 5;

int Cols = 5;

        Button[] buttons = new Button[Rows * Cols];
        int index = 0;
        for (int i = 0; i < Rows; i++)
        {
            for (int j = 0; j < Cols; j++)
            {
                Button b = new Button();
                b.Size = new Size(40, 55);
                b.Location = new Point(55 + j * 45, 55 + i * 55);
                b.BackColor = Color.Blue;
                buttons[index++] = b;
            }                
        }
        panel1.Controls.AddRange(buttons);

As simple as this

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int idx = rnd.Next(Rows * Cols);
    if (buttons[idx].BackColor == Color.Blue)
    {
        buttons[idx].BackColor = Color.Red;
        cnt++;
    }
}

You will use the Random class to choose an index value between 0 and 24 and use that index to select one of your blue buttons, if the selected button has a blue backcolor, change it to Red

By the way, this works because you don't really have a 2 dimension array here.
In case your array is declared as a 2 dimension array like here

Button[,] buttons = new Button[Rows, Cols];

then you need two random values at each loop, one for the row and one for the column

int cnt = 0;
Random rnd = new Random();
while (cnt < 5)
{
    int row = rnd.Next(Rows);
    int col = rnd.Next(Cols);

    if (buttons[row, col].BackColor == Color.Blue)
    {
        buttons[row, col].BackColor = Color.Red;
        cnt++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM