2015年10月30日 星期五

隨機變數nxn

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 ggwp
{
    public partial class Form1 : Form
    {
        const int n = 4,s=300;
        Button[,] buttons = new Button[n, n];
        int i, j,d;
        int width = s/n, height = s/n;
        int[,] matrix = new int[1, n*n];
        Random rnd = new Random();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                 
                    buttons[i, j] = new Button();
                    buttons[i, j].Location = new Point((i + 1) * s/n, (j + 1) * s/n);
                    buttons[i, j].Size = new Size(width, height);
                    buttons[i, j].Text = (i * n + j+1).ToString();
                 
                    this.Controls.Add(buttons[i, j]);
                }
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
         
            for (i = 0; i < n * n; i++)
            {
                matrix[0, i] = i+1;    
            }
            for (i = 0; i < n * n; i++)
            {
                int a = rnd.Next(1, n * n);
                int b = rnd.Next(1, n * n);
                int temp;
                temp = matrix[0, a];
                matrix[0, a] = matrix[0, b];
                matrix[0, b] = temp;
            }
            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                     buttons[i, j].Text = matrix[0, i * n + j].ToString();
                }
            }
        }
    }
}

沒有留言:

張貼留言