2016-10-07 37 views
-4

我有一個2d數組按鈕[5,5]所有藍色...如何隨機生成5個紅色按鈕在數組中...?如何生成一個隨機數......?在c#

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); 
+1

在這裏你去:https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c –

+2

這不是一個二維陣列... – Gusman

回答

2

,因爲這

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++; 
    } 
} 

您將使用Random class選擇0至24之間的指標值,並使用該索引來選擇您的藍色按鈕中的一個,如果所選擇的按鈕有這麼簡單藍色backcolor,將其更改爲紅色

順便說一句,這是有效的,因爲您在這裏確實沒有2維數組。
如果您的數組被聲明爲一個2維數組喜歡這裏

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

,那麼你需要在每個循環兩個隨機值,一個是一行和一對列

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++; 
    } 
} 
+0

該代碼是有缺陷的,它可以多次重複相同的索引。 – Gusman

+0

@Gusman現在我已經修復了原始問題 – Steve

+0

是的,我真的想要一個二維數組......非常感謝!我會嘗試第二個。 –