Okay this is probably more a maths question but since its related to programming and my web application i’ll ask here first:
I’m trying to create short id’s that are 8 characters long . The “pool” to draw the id from is a combination of numbers, upper and lower case letters.
string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz"
And if you’re interested here’s the method:
private string GenerateRandomCode(int length)
{
string charPool = "ABCDEFGOPQRSTUVWXY1234567890ZabcdefghijklmHIJKLMNnopqrstuvwxyz";
StringBuilder rs = new StringBuilder();
for (int i = 0; i < length; i++)
{
rs.Append(charPool[(int)(_random.NextDouble() * charPool.Length)]);
}
return rs.ToString();
}
How many possible combinations are there for 8 character id’s? Grateful if you can post the equation as well 🙂
Thanks
options per slot ^ number of slots = number of combinationsa-z is 26, times 2 (for uppers as well) is 52, plus 10 (0-9) is 62. Each ID is 8 chars long, so the result is 62^8, which is pretty big:
218,340,105,584,896 possible unique ID'sI would suggest doing:
_random.Next(charPool.Length - 1)(and saving
charPool.Length - 1in a variable outside of the loop), instead of:_random.NextDouble() * charPool.LengthBecause you might get an exact
1.0with.nextDouble(), which means you will be accessing the array at an index that equals the length, and you will get IndexOutOfRangeException.