Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created October 18, 2018 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/bc8b4a3d2e7ec35dc99ec12a9e022443 to your computer and use it in GitHub Desktop.
Save guitarrapc/bc8b4a3d2e7ec35dc99ec12a9e022443 to your computer and use it in GitHub Desktop.
Generate specific length random id.
void Main()
{
// conflict with following length. more than 7 is much stable.
// 5 = 50/100000
// 6 = 5/100000
// 7 = 0/100000
var rnd = new Random(Guid.NewGuid().GetHashCode());
var coupon = new string[100000];
var dup = 0;
for (var j = 0; j < 100; j++)
{
for (var i = 0; i < coupon.Length; i++)
{
coupon[i] = GenerateCoupon(7, rnd);
}
var count = coupon.Distinct().Count();
if (count != 100000)
{
count.Dump();
dup++;
}
j++;
}
dup.Dump();
}
// https://codereview.stackexchange.com/questions/5983/random-string-generation
public static string GenerateCoupon(int length, Random random)
{
var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var result = new StringBuilder(length);
for (var i = 0; i < length; i++)
{
result.Append(characters[random.Next(characters.Length)]);
}
return result.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment