检查是否已生成随机数
本文关键字:随机数 是否 检查 | 更新日期: 2023-09-27 17:59:20
如何在WinForms中使用C#生成6个随机但唯一的数字?
我有以下代码:
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 LottoGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int randnum = rnd.Next(1, 49); // creates a number between 1 and 49
MessageBox.Show(Convert.ToString(randnum));
}
}
}
我想确保生成的随机数不是重复的随机数。我如何编写逻辑来检查生成的数字是否与之前生成的另一个数字相同?如果是,则生成一个新的数字。
有道理吗?
生成具有[1;49]值的列表,对其进行混洗并逐个获取元素。
private List<int> list = null;
public Form1()
{
InitializeComponent();
Random rnd = new Random();
list = Enumerable.Range(1, 49).OrderBy(r => rnd.Next()).ToList();
}
private void button1_Click(object sender, EventArgs e)
{
if (list.Count == 0)
throw new InvalidOperationException();
int randnum = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
MessageBox.Show(randnum.ToString());
}
如果您只需要49个随机数中的6个,则可以添加.Take()
方法调用。
list = Enumerable.Range(1, 49).OrderBy(r => rnd.Next()).Take(6).ToList();
您需要将生成的数字保存在内存中,然后将新生成的数字与内存中的集合进行比较。
您可以使用在类级别定义的List<int>
,将随机数存储在列表中,并检查它是否已经存在于列表中。
List<int> list = new List<int>(); //defined at class level
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int randnum = rnd.Next(1, 49); // creates a number between 1 and 49
if (!list.Contains(randnum))
{
list.Add(randnum);
}
else
{
//duplicate number
}
MessageBox.Show(Convert.ToString(randnum));
}
如果你想要6个数字,那么你可以做:
Random rnd = new Random();
while (list.Count < 6)
{
int randnum = rnd.Next(1, 49); // creates a number between 1 and 49
if (!list.Contains(randnum))
{
list.Add(randnum);
}
else
{
//duplicate number
}
}
添加一个新容器来存储已生成的值。然后在生成您的号码时,检查它是否在您的列表中。如果是,请继续生成,直到它不在列表中为止。不过,由于您只能有49个不同的值,因此一旦生成了所有可能的值,就必须进行其他检查。
List<int> lstRan = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int randnum = rnd.Next(1, 49); // creates a number between 1 and 49
while (lstRan.Contains(randnum))
randnum = rnd.Next(1,49);
lstRan.Add(randnum);
MessageBox.Show(Convert.ToString(randnum));
}