posted 7/8/2010 by Raghav Khunger
In this blog I will explain how to generate n digit unique random numbers in C#. I have used "HashSet" collection and yield keywords in my below example which will help us in to group random numbers. As the random word comes there comes the "Random" class so below is the source code to generate random numbers.
#region Using Directives using System; using System.Collections.Generic; #endregion public class Example { class Test { static void Main() { foreach (var number in GetRandomNumbers(10,100)) { Console.WriteLine(number); } Console.ReadLine(); } static IEnumerable<int> GetRandomNumbers(int noOfRandomNumbers, int maxValue) { var mySet = new HashSet<int>(); for (int i = 0; i < noOfRandomNumbers; i++) { int randomNo = new Random().Next(maxValue); while (!mySet.Add(randomNo)) { randomNo = new Random().Next(maxValue); } yield return randomNo; } } } }
HashSet is a collection in unordered manner containing unique elements. You can refer for HashSet at here:http://msdn.microsoft.com/en-us/library/bb359438.aspx . It is fast and efficient as compare to "List". It is built to perform searching and inserting values in more efficient manner. So we are using HashSet as a container for storing random numbers. Now come to this method
static IEnumerable<int> GetRandomNumbers(int noOfRandomNumbers, int maxValue) { .................... }
This method accepts two argumenst. First one is the number of random numbers you need and second one denotes what is the maximum range or value of the random number which you want to generate. With the help of this code:
new Random().Next(maxValue);
we are generating random number. Next we have to add the reandom number in hash set collection
while (!mySet.Add(randomNo)) { randomNo = new Random().Next(maxValue); }
Above till we get the unique number which does not exists in the hash set we will will apply a loop. Next with the help of "yield" operator I am returning all of the unique random numbers. The "yield" has a big advantage that it provides Lazy Loading . For "yield" you can refer http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx . Okay now come back to above code, here are some of the outputs which I got while running it.
Test1
Test 2
try this ,
You can do using collection also. private string numbers() { var numbers = new Collection(); var rnd = new Random(); for (int i = 0; i < 10; i++) { var num= rnd.Next(1, 12); if (!numbers.Contains(num)) numbers.Add(num); else i--; } var sb = new StringBuilder(); int counter = 1; foreach (var i in numbers) { sb.AppendFormat("{0}.{1} ",counter++, i); } return sb.ToString(); }
Thanks
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18