Generating Unique Random Numbers in Java

后端 未结 21 2899
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  误落风尘
    2020-11-21 07:54

    Below is a way I used to generate unique number always. Random function generates number and stores it in textfile then next time it checks it in file compares it and generate new unique number hence in this way there is always a new unique number.

    public int GenerateRandomNo()
    {
        int _min = 0000;
        int _max = 9999;
        Random _rdm = new Random();
        return _rdm.Next(_min, _max);
    }
    public int rand_num()
    {
        randnum = GenerateRandomNo();
        string createText = randnum.ToString() + Environment.NewLine;
        string file_path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\Invoices\numbers.txt";
        File.AppendAllText(file_path, createText);
        int number = File.ReadLines(file_path).Count(); //count number of lines in file
        System.IO.StreamReader file = new System.IO.StreamReader(file_path);
        do
        {
            randnum = GenerateRandomNo();
        }
        while ((file.ReadLine()) == randnum.ToString());
        file.Close();
        return randnum;
    
    }
    

提交回复
热议问题