How to Generate Unique Number of 8 digits?

后端 未结 9 929
庸人自扰
庸人自扰 2020-12-30 01:39

I am using this code to generate a 8 digit unique number.

byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToUInt32(buffer, 8).ToString();
<         


        
相关标签:
9条回答
  • 2020-12-30 02:11

    Any random sequence is bound to have some collisions. It's just a matter of when. Using the birthday paradox formula, with 100,000,000 possible values (8 digits), the chance that you will have a collision with only 10,000 elements is around 40% and 99% with 30,000 elements. (see here for a calculator).

    If you really need a random sequence, you should not use a GUID for this purpose. GUIDs have very specific structure and should only be taken as a whole. It is easy enough to create a random 8 digit sequence generator. This should give you an 8 digit sequence:

     public string Get8Digits()
     {
       var bytes = new byte[4];
       var rng = RandomNumberGenerator.Create();
       rng.GetBytes(bytes);
       uint random = BitConverter.ToUInt32(bytes, 0) % 100000000;
       return String.Format("{0:D8}", random);
     }
    

    You can also take the RandomNumberGenerator and place it somewhere to avoid creating a new one everytime.

    0 讨论(0)
  • 2020-12-30 02:18

    My first answer did not address the uniqueness problem. My second one does:

    static int counter;
    public static int GetUniqueNumber()
    { 
        return counter++; 
    }
    

    If you want to have unique numbers across app restarts, you need to persist the value of counter to a database or somewhere else after each and every GetUniqueNumber call.

    0 讨论(0)
  • 2020-12-30 02:18

    This method will generate a random string, it doesn't rely on the Random method and also is far better than the guid approch :

    public static string gen_Digits(int length)
    {
        var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
        return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
    }
    

    you can increase the length for less collision chance, but to have a 100% unique sequence you have to persist the old generated values and check the newly created value for uniquness.

    0 讨论(0)
提交回复
热议问题