Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating multiple random numbers

I want to generate 25 unique random numbers and list them in a console. The numbers should be atleast 10 characters long. Any easy way to do that?

like image 541
Jasl Avatar asked May 31 '10 09:05

Jasl


2 Answers

Try building the numbers up as strings, and use a HashSet to ensure they are unique:

Random random = new Random();
HashSet<string> ids = new HashSet<string>();

while (ids.Count < 25)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10; ++i)
    {
        sb.Append(random.Next(10));
    }
    ids.Add(sb.ToString());
}

Example output:

7895499338
2643703497
0126762624
8623017810
...etc...

The class HashSet is present in .NET 3.5 and newer.

like image 109
Mark Byers Avatar answered Sep 30 '22 03:09

Mark Byers


The problem lies a little in "25 unique random". Displaying 25 random numbers is as easy as

Random r = new Random();
for(int i=0; i<25; i++)
    Console.WriteLine(r.Next(1,100).ToString());

These are not necessarily unique, though. If you do not want to allow duplicates, you need to store previously generated numbers somehow, and roll again if you hit an old one.

Be aware that you change the probability distribution of your generated numbers this way.

Edit: I've just noticed that these numbers should be ten characters long. Since 9,999,999,999 exceeds Int32.MaxValue, I'd suggest using Math.Floor(r.NextDouble() * 10000000000 + 1000000000) instead of r.Next(1,100).

Since your numbers are that long, you should not need to worry about duplicates. They are very very unlikely.

like image 31
Jens Avatar answered Sep 30 '22 03:09

Jens