C#C
C#3y ago
Kiraii

❔ Better way to do this random password generation program

This program generates a random password then removes duplicates and excludes some chars. I need suggestion on how to make it more efficient
{
  Console.Write("Length of pass : ");
  int len = int.Parse(Console.ReadLine());
  string password = RandomPassword<string>(new List<string> { upper, lower, number, symbol }, len);
  string uniquePassword = DuplicateRemoval<string>(password);
  string exclude = ExcludeSimilarChar(uniquePassword);
  Console.WriteLine("Password: " + uniquePassword);
  Console.WriteLine("After Excluding:" + exclude);
  }
 static string RandomPassword<T>(List<T> x, int len)
 {
 Random rand = new Random();
 char[] password = new char[len];
  for (int i = 0; i < len; i++)
     {
      string set_select = x[i % x.Count].ToString();
      int random_value = rand.Next(set_select.Length);
      password[i] = set_select[random_value];
      }
  return new string(password);
    }

static string DuplicateRemoval<T>(T str)
    {
     HashSet<char> set = new HashSet<char>();
     string password = str.ToString();
     for (int i = 0; i < password.Length; i++)
      {
      char c = password[i];
       if (!set.Add(c)) 
       {
        char newChar;
         do
          {
           newChar = RandomPassword<string>(new List<string> { upper, lower, number, symbol }, 1)[0];
          } while (!set.Add(newChar));
         password = password.Remove(i, 1).Insert(i, newChar.ToString());
            }
        }
        return password;
    }
    static string ExcludeSimilarChar<T>(T str)
    {
      List<char> unwanted = new List<char>() { 'L', 'l', 'o', 'O', '7', '1', '0' };
      string password = str.ToString();
      string result = "";
      foreach(char c in password) 
      {
       if(!unwanted.Contains(c))
        result += c;
      }
       return result;
    }
  static string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static string lower = "abcdefghijklmnopqrstuvwxyz";
  static string number = "0123456789";
  static string symbol = "!@#$%^&*()";
}
Was this page helpful?