c# - 每次都会生成唯一的随机数吗?
问题描述
下面我编写了一个运行良好的代码并生成一个随机数,它的工作逻辑是在返回随机数之前它将随机数与文本文件中已经生成的数字进行比较。我想保证它每次都会产生唯一的随机数吗?
public int GenerateRandomNo()
{
int _min = 0000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
public int rand_num()
{
string file_path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Invoices\numbers.txt";
int number = File.ReadLines(file_path).Count(); //count number of lines in file
System.IO.StreamReader file = new System.IO.StreamReader(file_path);
if (number == 0)
{
randnum = GenerateRandomNo();
}
else
{
randnum = GenerateRandomNo();
for (int a = 1; a <= number; a++)
{
if ((file.ReadLine()) == randnum.ToString())
randnum = GenerateRandomNo();
}
file.Close();
}
createText = randnum.ToString() + Environment.NewLine;
File.AppendAllText(file_path, createText);
file.Close();
return randnum;
}
如果他们的代码需要任何改进,请告诉我。因为我想完全确保它总是会生成唯一的随机数。
解决方案
这是执行此任务的一种非常有效的方法:
private Random rnd = new Random();
public int rand_num()
{
string exe_path = System.Windows.Forms.Application.ExecutablePath;
string exe_folder = System.IO.Path.GetDirectoryName(exe_path);
string file_path = System.IO.Path.Combine(exe_folder, "Invoices\numbers.txt");
var number =
Enumerable
.Range(0, 10000)
.Except(File.ReadAllLines(file_path).Select(x => int.Parse(x)))
.OrderBy(x => rnd.Next())
.First();
File.AppendAllLines(file_path, new [] { number.ToString() });
return number;
}
它生成所有数字的列表Enumerable.Range(0, 10000)
。然后它会删除它已经在文本文件中找到的数字.Except(File.ReadAllLines(file_path).Select(x => int.Parse(x)))
。然后它随机排序剩余的数字(就像洗一包纸牌).OrderBy(x => rnd.Next())
,最后它只选择第一个数字.First();
。
推荐阅读
- pandas - 如何使用 matplotlib 针对日期时间索引在 Pandas 中仅绘制数据框的单列
- c - C不为新的char数组分配内存
- c# - 如何使用 DateTime 将变量作为参数传递
- oracle-sqldeveloper - 故障排除错误消息。无效的密码
- r - 为什么 as.integer 不能正确更改数据
- java - 如何使用 A METHOD 将数据库 ex(team1,team2,..) 中的列表带到组合框
- html - 为什么 Chrome 开发工具显示我在视觉检查器上填充而不是实际样式?
- excel - VBA 在 Word 对象上使用 Excel 版本的查找?
- javascript - 通过正文单击打开窗口弹出器
- java - 无法使用 @AllArgsConstructor 访问构造函数,但可以使用 @RequiredArgsConstructor