首页 > 解决方案 > 每次都会生成唯一的随机数吗?

问题描述

下面我编写了一个运行良好的代码并生成一个随机数,它的工作逻辑是在返回随机数之前它将随机数与文本文件中已经生成的数字进行比较。我想保证它每次都会产生唯一的随机数吗?

    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;

    }

如果他们的代码需要任何改进,请告诉我。因为我想完全确保它总是会生成唯一的随机数。

标签: c#.net

解决方案


这是执行此任务的一种非常有效的方法:

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();


推荐阅读