Using the random selection method, we select elements with equal probability of selection, respecting the rule that no element in the iteration is omitted. However, the algorithm doesn't always follow that rule.
In this example:
[HttpPost("PasswordGenerator")]
public string GeneratePassword()
{
const string symbols = "!@#$%^&*()[]{}|;:,<>?";
const string numbers = "0123456789";
const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const string allChars = symbols + numbers + letters;
Random random = new();
try
{
char[] passwordArray = allChars.ToCharArray();
for (int i = passwordArray.Length-1; i > 0; i--)
{
int j = random.Next(i+1);
(passwordArray[i], passwordArray[j]) = (passwordArray[j], passwordArray[i]);
}
return new string(passwordArray);
}
catch
{
return new string("nema passworda");
}
}
I want to generate a random password from the given characters. In the beginning there are strings which I concat then break into an array of single characters.
Algorithm start its job from a for loop where it picks a last character on the last index (if the last index is 21, the picked character is z)
int i = passwordArray.Length-1; i > 0; i--
i-- tells us that is going backward, not forward.
int j = random.Next(i+1); is a randomly picked index between given span of indexes (if the i+1 = 10, than j has to be some random index picked between 0 and 10).
(passwordArray[i], passwordArray[j]) = (passwordArray[j], passwordArray[i]); --> this is called a tuple swap method which literally just swaps the positions. The right side (passwordArray[j], passwordArray[i]) creates a tuple with those two values, then the left side deconstructs it back into the array positions in reverse order.
Top comments (0)