2015年10月23日 星期五

不產生重複變數

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Button[,] buttons = new Button[3, 3];     //宣告一個二維陣列  (用來製造4x4按鈕)
        int[] randomize = new int[9];                //宣告一個一維陣列  (用來存取變數的陣列)
        Random rnd = new Random();                //宣告產生亂數
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            for (int i = 0; i < 3; ++i)
            {

                for (int j = 0; j < 3; ++j)
                {
                    buttons[i, j] = new Button();                  //利用二維陣列產生4x4按鈕
                    buttons[i, j].Location = new Point(i * 100, j * 100);     //改變其按鈕位置
                    buttons[i, j].Size = new Size(100, 100);            //改變按鈕大小

                    this.Controls.Add(buttons[i, j]);     //要產生按鈕一定要有這行

                }
            }
        }

        private void button1_Click(object sender, EventArgs e)   //按下button1就可以產生亂數
        {
            for (int i = 0; i < 9; i++)
            {

                randomize[i] = rnd.Next(0, 9);        //將0~15個亂數依序放進一維陣列randomize中

                for (int j = 0; j < i; j++)
                {
                    while (randomize[j] == randomize[i])         // 檢查是否有重複的亂數 如果有就重新產生
                    {
                        j = 0;
                        randomize[i] = rnd.Next(0, 9);
                    }
                }
            }

            for (int i = 0; i < 3; ++i)
            {

                for (int j = 0; j < 3; ++j)
                {
                    buttons[i, j].Text = Convert.ToString(randomize[i * 3 + j]);            //將一維陣列randomize依序放進二維陣列的按鈕上
                    this.Controls.Add(buttons[i, j]);

                }
            }

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }
    }
}






沒有留言:

張貼留言