2014年12月5日 星期五

第十一周-亂數不重複

(1)

(2)
 (3)


//===========================================================
        static int n = 4; // 按鈕數量總共有 n*n 個
        Button[,] buttons = new Button[n,n];
        Button rnd_button = new Button();
        System.Random r = new System.Random();
        private void Form1_Load(object sender, EventArgs e)
        {
            //--Form------------
            this.Width = 1000;
            this.Height = 1000;
            //--Buttons---------
            int button_width = 50, button_height = 50,name=0;
            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)
                {
                    name++;
                    buttons[i, j] = new Button();
                    buttons[i, j].Location = new Point(j * 50, i * 50);
                    buttons[i, j].Size = new Size(button_width, button_height);
                    buttons[i, j].Text = name.ToString();
                    this.Controls.Add(buttons[i, j]);  //Show button
                }
            //--rnd_Button-----
            rnd_button.Location = new Point(300, 0);
            rnd_button.Text = "重新排列";
            rnd_button.Click += rnd_button_Click;
            this.Controls.Add(rnd_button);
        }
        void rnd_button_Click(object sender, EventArgs e)
        {
            //--Setting Random name--
            string[] Rnd_name = new string[n * n + 1];
            for (int i = 1; i <= n * n; i++) Rnd_name[i] = i.ToString();
            for (int i = 1; i <= n * n; i++)
            {
                string tmp = ""; int rnd = r.Next(1, n * n);
                tmp = Rnd_name[Rnd_name.Length - 1];
                Rnd_name[Rnd_name.Length - 1] = Rnd_name[rnd];
                Rnd_name[rnd] = tmp;
            }
            //--Rename--
            for (int i = 0, k = 1; i < n; i++)
                for (int j = 0; j < n; j++)
                {
                    buttons[i, j].Text = Rnd_name[k];
                    k++;
                }
            //------------
        }
        //===========================================================

沒有留言:

張貼留言