C#實現的簡單的隨機抽號器

沐煜歆羨發表於2020-12-24

由於老師需要,讓我寫一個隨機抽號器,,就很簡單的寫一個,用C#寫的。主要依靠random來實現一個隨機數以及list可變長陣列實現的。
由於專案難度不大,我就直接放程式碼了。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace 隨機抽號器
{
public partial class Form1 : Form
{
private int person_number=0;
private int time = 1;
private List arr = new List();
public Form1()
{
InitializeComponent();
Thread thread = new Thread(set_index);
thread.IsBackground = true;
thread.Start();
button3.Enabled = false;
}

    private void set_index()
    {
        while (true)
        {
            Random rd = new Random(Convert.ToInt32(DateTime.Now.ToString("ddHHmmss", DateTimeFormatInfo.InvariantInfo)));
            while (person_number != 0)
            {
                Random rd2 = new Random(rd.Next(1, 65535) - rd.Next(1, 65535));
                int side = rd2.Next(1, person_number + 1);
                if (!arr.Contains(side))
                {
                    arr.Add(side);
                }
            }

            if (person_number == arr.Count && person_number!=0&&arr.Count!=0)
            {
                break;
            }
            Thread.Sleep(1000);
        }
    
    }

    private void button1_Click(object sender, EventArgs e)
    {
        button3.Enabled = true;
        if (textBox1.Text == "")
        {
            MessageBox.Show("請先輸入人數!");
        }
        else {
            person_number =Convert.ToInt32(textBox1.Text);
            richTextBox1.AppendText("成功選擇人數!當前抽號人數:" + textBox1.Text + "人\r\n");
            button1.Enabled = false;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText("\r\n成功清空當前人數,請重新選擇人數!\r\n\r\n");
        button1.Enabled = true;
        button3.Enabled = true;
        person_number = 0;
        time = 1;
        arr.Clear();
        Thread thread = new Thread(set_index);
        thread.IsBackground = true;
        thread.Start();

    }

    private void button3_Click(object sender, EventArgs e)
    {
        richTextBox1.AppendText("第" + time.ToString() + "個人的工號是:" + arr[0] + "\r\n");
        arr.RemoveAt(0);
        if ((time)== person_number) {
            button3.Enabled = false;
            richTextBox1.AppendText("操作完成!所有工號已分配!");
        }
        time++;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        richTextBox1.Clear();
    }
}

}

執行效果
在這裡插入圖片描述

相關文章