Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random, unique values C#

I've searched for a while and been struggling to find this, I'm trying to generate several random, unique numbers is C#. I'm using System.Random, and I'm using a DateTime.Now.Ticks seed:

public Random a = new Random(DateTime.Now.Ticks.GetHashCode()); private void NewNumber() {     MyNumber = a.Next(0, 10); } 

I'm calling NewNumber() regularly, but the problem is I often get repeated numbers. Some people suggested because I was declaring the random every time I did it, it would not produce a random number, so I put the declaration outside my function. Any suggestions or better ways than using System.Random ? Thank you

like image 342
Christian Peut Avatar asked Jan 23 '13 05:01

Christian Peut


People also ask

How do you create an array with unique numbers?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values.

How do you generate unique random numbers in C++?

rand() rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.


1 Answers

I'm calling NewNumber() regularly, but the problem is I often get repeated numbers.

Random.Next doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:

public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());                                 // Since similar code is done in default constructor internally public List<int> randomList = new List<int>(); int MyNumber = 0; private void NewNumber() {     MyNumber = a.Next(0, 10);     if (!randomList.Contains(MyNumber))         randomList.Add(MyNumber); } 
like image 66
Habib Avatar answered Oct 02 '22 10:10

Habib