练习:
上一篇博客使用LIST集合来存储随机数,但是LIST<>可以存储重复数据,也就是说在选定区间内多次使用随机数可能出现重复,
例如从1到10选9个数那么很大概率会选取重复的数字。
暂时没想出有什么好办法可以解决随机数重复的问题
偶然间发现HashSet<>的Add()方法不可以写入重复元素,随机数重复的问题也就迎刃而解了。
美中不足的是HashSet中的元素是无序的。。。
从下面可以看到没有重复,但是数字的没有排序。。。不知道这个问题如何解决
直接复制过来代码:
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 抽号
{
public partial class NumForm : Form
{
public NumForm()
{
InitializeComponent();
}
public void c()
{
txtFrom.Text = "";
txtQuan.Text = "";
txtRe.Text = "";
txtTo.Text = "";
}
private void timer1_Tick(object sender, EventArgs e)
{
//星星
lblTop.Text = lblTop.Text.Substring(1) + lblTop.Text.Substring(0, 1);
}
///开始按钮
private void btnStart_Click(object sender, EventArgs e)
{
if (txtFrom.Text == "" | txtTo.Text == "" | txtQuan.Text == "")
{
MessageBox.Show("请输入完整信息");
return;
}
int x = int.Parse(txtFrom.Text);
int y = int.Parse(txtTo.Text);
int n = int.Parse(txtQuan.Text);
HashSet<int> Set = new HashSet<int>();
Random r = new Random();
aa: for (int i = 1; i <= n; i++)
{
Set.Add(r.Next(x, y + 1));
}
if (n != Set.Count)
{
Set.Clear();
goto aa;
}
foreach (int a in Set)
{
txtRe.Text += "--" +a.ToString()+"--";
}
}
private void NumForm_Load(object sender, EventArgs e)
{
this.ActiveControl = this.txtFrom;
}
private void btnReset_Click(object sender, EventArgs e)
{
c();
}
}
}