2015年10月30日 星期五

亂數不重複

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        int a = 3, b,t;
        int[] rand = new int[16];
        Button[,] buttons = new Button[4, 4];
        Random randomc1 = new Random(Guid.NewGuid().GetHashCode());

        public Form1()
        {
            InitializeComponent();


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; ++i)
            {

                for (int j = 0; j < 4; ++j)
                {
                    buttons[i, j] = new Button();
                    buttons[i, j].Location = new Point(i * 80, j * 80);
                    buttons[i, j].Size = new Size(80, 80);

                    this.Controls.Add(buttons[i, j]);

                }
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {


        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void button11_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
           

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

                rand[i] = randomc1.Next(1, 17);

                for (int j = 0; j < i; j++)
                {
                    while (rand[j] == rand[i])
                    {
                        j = 0;
                        rand[i] = randomc1.Next(1, 17);
                    }
                }
            }

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

                for (int j = 0; j < 4; ++j)
                {
                    buttons[i, j].Text = Convert.ToString(rand[i * 4 + j]);

                }
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            for (int i = 0; i < 16; i++)
            {
                for (int j = 0; j < 16; j++)
                {
                    if (rand[i] > rand[j])
                    {
                        t = rand[i];
                        rand[i] = rand[j];
                        rand[j] = t;
                    }
                }

            }
            for (int i = 0; i < 4; ++i)
            {

                for (int j = 0; j < 4; ++j)
                {
                    buttons[i, j].Text = Convert.ToString(rand[i * 4 + j]);

                }
            }
        }
    }
}

沒有留言:

張貼留言