Last active
November 7, 2018 07:12
-
-
Save geniuszxy/104d2a5192c5b0b8ba500b0ac0609eae to your computer and use it in GitHub Desktop.
Random Id Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IdGenerater | |
{ | |
private string[] charss = //generated by RandChars | |
{ | |
"47eRaiGQZHjXPnxh2dfUYbDmN986ycTSvkLuKoJtApWqEMwzFCVr3gs5B", | |
"6BD28rJaZzqTEjVQsUvNMLfimWG5k94gbK3wyhXPSpxucotHeFCYAdR7n", | |
"RijAmWYBHtkwJP8K4bgMN5GDFX6zLZsqUhueyEVpdxSa7ocQvTnr32fC9", | |
"xeuNs75AhUSFkM4TmCZgEtKHDX6QjiG9RvL8opqwadJBcyPYrb3WnzV2f", | |
"XNQisGdLDSU4Wx2V5PczY8MahpHnuy6j3fvFEAqrTJmRgZk9btw7KBoeC", | |
"qTmR5btpxP8wGEa6i4zVZurJg7hKysdoMnDFUeX3SCWH2kjc9QfBYNLAv", | |
}; | |
private const int CHARS_LENGTH = 57; | |
private int[] indexes = new int[6]; | |
private char[] chars = new char[6]; | |
public int[] Generate(int id) | |
{ | |
int p = 0; | |
if (id < 0) | |
throw new ArgumentOutOfRangeException("id"); | |
while (id >= CHARS_LENGTH) | |
{ | |
int rem = id % CHARS_LENGTH; | |
indexes[p++] = rem; | |
id = (id - rem) / CHARS_LENGTH; | |
} | |
indexes[p] = id; | |
return indexes; | |
} | |
public string GenerateString(int id) | |
{ | |
var indexes = Generate(id); | |
int index = 0; | |
//TODO add proof: the random indexes are still unique | |
for (int i = 0; i < indexes.Length; ++i) | |
{ | |
index += indexes[i]; //higher index is also random | |
chars[i] = charss[i][index % CHARS_LENGTH]; | |
} | |
return new string(chars); | |
} | |
} | |
//Generate random character sequence | |
class RandChars | |
{ | |
const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; //57 chars | |
private Random _rnd = new Random(); | |
public void Generate() | |
{ | |
var charArr = chars.ToCharArray(); | |
Comparison<char> comparer = RandomComparer; | |
for (int i = 0; i < 6; ++i) | |
{ | |
Array.Sort(charArr, comparer); | |
Console.WriteLine(new string(charArr)); | |
} | |
} | |
private int RandomComparer(char c1, char c2) | |
{ | |
return _rnd.Next().CompareTo(_rnd.Next()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment