1

I generate a string with 62 options ^ 6 letters = 56,800,235,584

But when running the code, it repeats the same string less then every 200,200 times

What is the problem here?

BTW: This code is based on the answer here

class Program
{
    static void Main(string[] args)
    {
        var d = new Dictionary<string, bool>();

        for (int i = 0; ; i++)
        {
            var s = GenerateString(6);
            try
            {
                d.Add(s, false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("{0} - {1} - {2}", i, s, ex.Message));
                i = 0;
            }
        }

        Console.ReadKey();
    }


    static Random _rnd = new Random();
    public static string GenerateString(int len)
    {
        const string bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string smallLetters = "abcdefghijklmnopqrstuvwxyz";
        const string numbers = "1234567890";

        var validChars = bigLetters + smallLetters + numbers;

        var result = new StringBuilder();

        for (int i = 0; i < len; i++)
        {
            result.Append(validChars[_rnd.Next(validChars.Length)]);
        }

        return result.ToString();
    }
}
Community
  • 1
  • 1
Yacov
  • 1,060
  • 14
  • 27

2 Answers2

6

There is all OK with random.

The problem is related with Birthday paradox. When you have 200k items one of them could repeat.

Random string doesnt garantee always unique result. For unique results you should use GUID's.

Mitklantekutli
  • 410
  • 1
  • 3
  • 16
  • 1
    Just as a note for people reading this, GUID's are not guaranteed to not repeat, they are just very unlikely to because the number of possible outputs is so high. If you need to guarantee unique values, you will still need to check each new GUID against all of the previous values to make sure it isn't a repeat – Kevin Jan 18 '16 at 20:31
1

To avoid repeatation you can do a check for existence before adding the string to the list:

After for loop in GenerateString()

if(d.Contains(result.ToString()) // check whether the current generated string is in the list
 {
   GenerateString(len); // if it is already existed generate another one
 }
else
 { 
   return result.ToString(); // if not then return the string
 }
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88