I’ve created a “random password generator” app (I’m a beginner, just for practicing) and somehow at first button click it only fills 5-6-7 elements of my array.
This code might be strange (for generating random characters), I just looked ASCII table and searched for numbers, letters and I’ve put them into random min and max number.
string[] ch = new string [11];
Random r = new Random();
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 9; i++)
{
if (Convert.ToInt64(r.Next()) % 3 == 0)
ch[i] = Convert.ToString(Convert.ToChar(r.Next(49, 57)));
else if (Convert.ToInt64(r.Next()) % 3 == 1)
ch[i] = Convert.ToString(Convert.ToChar(r.Next(65, 89)));
else if (Convert.ToInt64(r.Next()) % 3 == 2)
ch[i] = Convert.ToString(Convert.ToChar(r.Next(97, 122)));
}
pass.Text = (Convert.ToString(ch[0] + "" + ch[1] + "" + ch[2] + "" + ch[3] + "" + ch[4] + "" + ch[5] + "" + ch[6] + "" + ch[7] + "" + ch[8] + "" + ch[9]));
To decide to use number (ascii 49-57) small letters (65-89) or bigs (97-122) I just made a random number then (truncating divided?) divided by 3 and result is then 0,1 or 2 then made ifs for them.
Might be stupid but its my own idea. So when I click on the button, at first time it shows only about 5,6,7 elements of arrays. Anybody knows why?
It’s not only the first time that the code fails to put values in all positions.
You have this control structure:
As you are picking a new random number for each condition, there is a 29.63% chance that neither of them will be true.
If you watch the result closely, you will see that most of the time there are some characters that don’t change.
You should pick one random number and check its value:
A different approach would be to put all the characters that you want to use in a string, and pick from that:
This is especially useful if you want to exclude some characters that are easy to mix up, like 0, O, o, 1 and l, then you just exclude them from the string: